mybatis-Spring 官网: http://www.mybatis.org/spring/zh/index.html
目录结构
1.配置meaven项目pom.xml
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.3.18.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>4.3.18.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.3.18.RELEASEversion>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.18.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>cglibgroupId>
<artifactId>cglibartifactId>
<version>2.2.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
dependencies>
按顺序写入settings(延迟加载),typeAliases(别名),environments (数据库链接),mappers(映射器)
<configuration>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
settings>
<typeAliases>
<typeAlias type="com.pb.entity.Student" alias="Student"/>
<typeAlias type="com.pb.entity.Classes" alias="Classes"/>
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:///springjdbc"/>
<property name="username" value="root"/>
<property name="password" value="111"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.pb.mapper"/>
mappers>
configuration>
我们将声明2个mapper文件位列
StudentMapper.xml(xml配置文件) StudentMapper.java(接口文件)
ClassesMapper.xml(xml配置文件) ClassesMapper.java(接口文件)
<mapper namespace="com.pb.mapper.StudentMapper">
<resultMap type="Student" id="StudentResultMapper">
<id column="id" property="id"/>
<result column="stuname" property="name"/>
<result column="age" property="age"/>
<result column="brithday" property="bd"/>
resultMap>
<select id="selectAll" resultMap="StudentResultMapper">
select * from Student
select>
<insert id="insertStudent" parameterType="student" >
insert into Student(stuname,age,brithday)values(#{name},#{age},now())
insert>
mapper>
ClassesMapper接口文件就不展示了,太华丽和StudentMapper接口一样的美丽,并且还没这个多(微笑)
public interface StudentMapper {
List<Student> selectAll();
void insertStudent(Student student);
}
<mapper namespace="com.pb.mapper.ClassesMapper">
<resultMap type="Classes" id="ClassesResultMapper">
<id column="class_id" property="id"/>
<result column="class_name" property="name"/>
resultMap>
<select id="selectAll" resultMap="ClassesResultMapper">
select * from class
select>
mapper>
创建Spring配置文件applicationContext.xml
applicationContext勾选context,aop,bean,tx
1.创建数据库连接池
2配置sqlSessionfactory 将数据库连接池和mybatis配置文件整合导入
3.配置类映射器的接口
5配置service(spring测试类getBean获取)
6配置事务管理器
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"
value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///springjdbc" />
<property name="username" value="root" />
<property name="password" value="111" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.pb.mapper" />
bean>
<bean id="studentService" class="com.pb.service.StudentServicelmpl">
<property name="studentMapper" ref="studentMapper" />
bean>
<bean id="classesService" class="com.pb.service.ClassesServicelmpl">
<property name="classesMapper" ref="classesMapper" />
bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="*" propagation="SUPPORTS" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="productServiceMethods" expression="execution(* com.pb.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/>
aop:config>
beans>
说明一下调用的顺序: controller代码 1.serivce层替换 2 事务管理 3.service层
StudentMapper(相当于dao层)public class StudentServicelmpl implements StudentService {
StudentMapper studentMapper;
public void setStudentMapper(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
@Override
public List<Student> selectAll(){
return studentMapper.selectAll();
}
public void insertStudent(Student student) {
studentMapper.insertStudent(student);
}
}
public interface StudentService {
List<Student> selectAll();
void insertStudent(Student student);
}
public class ClassesServicelmpl implements ClassesService {
ClassesMapper classesMapper;
public void setClassesMapper(ClassesMapper classesMapper) {
this.classesMapper = classesMapper;
}
@Override
public List<Classes> selectAll() {
return classesMapper.selectAll();
}
}
public interface StudentService {
List<Student> selectAll();
void insertStudent(Student student);
}
@Controller //在usermvc-servlet.xml内定义controller注解
public class StudentController {
StudentService studentService;
@Resource(name="studentService") //声明是哪个bean
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
// @RequestMapping(value="index.do",method=RequestMethod.GET) 也可以进入 不区分get post
@RequestMapping("/index")
public String index(Model model) {
List<Student> students=studentService.selectAll();
model.addAttribute("students", students);
return "index";
}
@RequestMapping("/insert")
public String insert(Student stu,Model model) {
studentService.insertStudent(stu);
return "redirect:index.do";
}
}
@Controller
public class ClassesController {
ClassesService classesService;
@Resource(name="classesService")
public void setStudentService(ClassesService classesService) {
this.classesService = classesService;
}
@RequestMapping("/index2")
public String index2(Model model) {
List<Classes> classes=classesService.selectAll();
model.addAttribute("classesService",classes);
return "index";
}
}
配置usermvc-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.pb.controller">context:component-scan>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">
<property value="org.springframework.web.servlet.view.JstlView" name="viewClass"/>
<property value="/" name="prefix"/>
<property value=".jsp" name="suffix"/>
bean>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.pb.common.String2Date">bean>
set>
property>
bean>
<mvc:annotation-driven conversion-service="conversionService" />
beans>
配置 web.xml
<servlet>
<servlet-name>usermvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>usermvcservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
主要是在配置文件上小新同学比较容易范一些小错误,命名不规范,大小写不统一的问题
--------------注解实现service层+事务管理
首先我们修改applicationContext.xml 声明context <!--声明使用注解实现service的位置
<bean id="studentService" class="com.pb.service.StudentServicelmpl">
<property name="studentMapper" ref="studentMapper" />
</bean>
<bean id="classesService" class="com.pb.service.ClassesServicelmpl">
<property name="classesMapper" ref="classesMapper" />
</bean>
-->
<context:component-scan base-package="com.pb.service"></context:component-scan>
修改applicationContext.xml 事务声明我们只需要这些 <!-- 6配置事务管理器
声明的事务管理对象是不能使用注解的
-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 把注解引入到这里或是说允许使用注解 并告诉他事务管理器是谁 -->
<tx:annotation-driven transaction-manager="txManager"/>
@Service("studentService")//声明相当于id="studentService"
//@Controller servlet层
//@Component 其他层 (监听器\过滤器)
//@Repository dao层
@Transactional(propagation=Propagation.REQUIRED)//确定了切入点(默认所有事务开启),查询不需要单独声明关闭
public class StudentServicelmpl implements StudentService {
StudentMapper studentMapper;
@Resource(name="studentMapper")//相当于配置service的