最近学习了,SSM框架,MyBatis感觉比较简单,边看边写两三天, 只能说是知道怎么用,还不敢说有多深的理解; Spring 呢,就比较复杂了, 理论的讲解有好多,我这性子耐不住,就直接上手;利用课余时间,大概一个星期,才能基本使用;不得不说,还是多写代码管用; 在这里对最近学的进行一系列总结,以后忘了的时候还能翻过来看看;
(一)创建项目
创建maven 项目,archetype 选webapp ;生成后在main下建一个java文件夹,标记为Sources Root
在pom.xml中添加必要的依赖
db.properties :
##########//jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
##########//c3p0
maxPoolSize=200
minPoolSize=5
initialPoolSize=10
checkoutTimeout=300000
log4j.properties :
# ERROR ----> WARN ---> INFO ---> DEBUG
log4j.rootLogger=DEBUG, stdout, logfile
# stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.logger.org.apache=DEBUG
# logfile
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=asset.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%p %d %F %M %m%n
log4j.logger.org.apache=DEBUG
(二)mybatis配置
创建一个mybatis.xml文件,对mybaits进行配置
< ?xml version="1.0" encoding="UTF-8" ?>
< !DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
< configuration>
<typeAliases>
<typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yihaomen/mybatis/model/User.xml"/>
</mappers>
< /configuration>
然后建立model、mapper、test包;
Main中的测试代码:
public class Main {
//
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static{
try{
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}catch(Exception e){
e.printStackTrace();
}
}
public static SqlSessionFactory getSession(){
return sqlSessionFactory;
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student stu = studentMapper.selStudentById(1);
System.out.println(stu);
} finally {
session.close();
}
}
}
(三)Spring
创建applicationContext.xml文件
配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置Controller扫描 -->
<context:component-scan base-package="com" />
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxPoolSize" value="${maxPoolSize}" />
<property name="minPoolSize" value="${minPoolSize}" />
<property name="initialPoolSize" value="${initialPoolSize}" />
<property name="checkoutTimeout" value="${checkoutTimeout}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池-->
<property name="dataSource" ref="dataSource"/>
<!--configLocation属性指定mybatis的核心配置文件-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--配置Mapper扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置Mapper扫描包 -->
<property name="basePackage" value="com.mapper" />
</bean>
</beans>
在使用了Spring后,spring 的配置文件完全可以取代mybatis的配置文件,可以把configuration 下的配置删除,但是在配置sqlSessionFactory时还要加载,所以有一个空的mybatis文件;数据源也都在spring 中配置;
同样在Main中测试:
public class Main{
private static ApplicationContext ctx;
static
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static void main(String[] args)
{
StudentMapper mapper = (StudentMapper) ctx.getBean("studentMapper");
//测试id=1的用户查询,根据数据库中的情况,可以改成你自己的.
System.out.println("得到用户id=1的用户信息");
Student stu = mapper.selStudentById(1);
System.out.println(stu);
}
}
这里还没有用到注释,后面会使用;
(四)spring-mvc
spring-mvc.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置Controller扫描 -->
<context:component-scan base-package="com.controller" />
<!-- 配置注解驱动 -->
<mvc:annotation-driven />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
还需要配置web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器加载spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置过滤器,解决post的乱码问题 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 配置springmvc什么时候启动,参数必须为整数 -->
<!-- 如果为0或者大于0,则springMVC随着容器启动而启动 -->
<!-- 如果小于0,则在第一次请求进来的时候启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 所有的请求都进入springMVC -->
<url-pattern>/</url-pattern>
</servlet-mapping>
不要忘记添加Tomcat
编写一个controller 测试
@Controller
@RequestMapping("/main")
public class StudentController {
@Autowired
private StudentMapper studentMapper;
@RequestMapping("/sel")
public String selStudentById(Student stu){
stu = studentMapper.selStudentById(1);
System.out.println(stu);
return "success";
}
}
index.jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/main/sel" >aaaaa</a>
</body>
</html>
success.jsp 随便写点就可以 点击链接能跳转到success.jsp 就说明成功了;
(五)出现的问题及解决
这些问题都是比较常见的,刚学的时候困扰了我好久,写出来也给自己记录一下;
1) 找不到mapper.xml 文件
写代码的时候,或者反向生成的 mapper接口和mapper.xml经常放在同一个包下,然后就发现运行会找不到xml文件;
查了几个帖子 有两种解决办法
1> 在resources建立与java下mapper 同样的目录,mapper.xml 放在此目录下; 因为某些原因,项目在编译时会忽略java路径下的xml文件;
2>比较省事的做法 在pom.xml中添加配置,
1. <resources>
2. <resource>
3. <directory>src/main/java</directory>
4. <includes>
5. <include>**/*.xml</include>
6. </includes>
7. <filtering>false</filtering>
8. </resource>
9. </resources>
这样就能找到java下的xml文件了;
2)自动扫描mapper
起初使用mybatis时 需要对每一个mapper 写一个MapperFactoryBean 太过繁琐
使用MapperScannerConfigurer 自动扫描
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.mybatis.spring.sample.mapper" />
</bean>
自动扫描注入 默认名字是接口名,首字母小写
(3)别名
别名,对包下的类默认 首字母小写
<typeAliases>
<package name="cn.lxc.vo" />
</typeAliases>
暂时这些,有几个记不清了 先到再补充