Spring和MyBatis的整合

Spring和MyBatis的整合

1 下载Spring整合Mybatis的依赖包,创建工程、增加依赖
2 创建Spring和MyBatis的配置文件

<?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>

	
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">


</beans>

3 创建项目实体类

package com.oupeng.pojo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable{
	private Integer id;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	private String userCode; 
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	private String userName; 
	private String userPassword; 
	private Integer gender; 
	private Date birthday; 
	private String phone; 
	private String  address;
	private Integer userRole;
	private Date creationDate ;
	private Integer createdBy; 
	private  Integer modifyBy;  
	private  String userRoleName;

	public String getUserRoleName() {
		return userRoleName;
	}
	public void setUserRoleName(String userRoleName) {
		this.userRoleName = userRoleName;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	private Date modifyDate;  
	private String idPicPath;  
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getUserRole() {
		return userRole;
	}
	public void setUserRole(Integer userRole) {
		this.userRole = userRole;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	
	public String getIdPicPath() {
		return idPicPath;
	}
	public void setIdPicPath(String idPicPath) {
		this.idPicPath = idPicPath;
	}
	public String getWorkPicPath() {
		return workPicPath;
	}
	public void setWorkPicPath(String workPicPath) {
		this.workPicPath = workPicPath;
	}
	private String workPicPath;
}

4 创建数据访问层接口

package com.oupeng.dao;

import java.util.List;

import com.oupeng.pojo.User;

public interface UserMapper {
       //查询所有的用户
	public List<User> getUserList(User user);
	//插入用户
	public int add(User user);
}

实现映射文件(.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <!-- nameSpace相当于一个文件夹,用来找映射文件   接口  里面id和接口的方法名相同;resultType表示方法返回值-->
  
  <mapper namespace="com.oupeng.dao.UserMapper">
	<!-- 配置查询 -->
	<select id="getUserList" parameterType="User"
		resultMap="userList">
		select u.*, r.roleName from smbms_user u,smbms_role r where u.userName like
		concat('%',#{userName},'%') and u.userRole=#{userRole} and
		u.userRole=r.id
	</select>

	<resultMap type="User" id="userList">
		<result property="userCode" column="userCode" />
		<result property="userName" column="userName" />
		<result property="userRoleName" column="roleName" />
	</resultMap>
	
	<insert id="add" parameterType="User">
	insert into smbms_user(userCode,userName,gender,address)values(#{userCode},#{userName},#{gender},#{address})
   </insert>
  </mapper>

5 创建数据访问层实现类
增加特殊的整合类:SqlSessionTemplate

package com.oupeng.dao.impl;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.oupeng.dao.UserMapper;
import com.oupeng.pojo.User;

public class UserMapperImpl implements UserMapper {
     //增加特殊的整合类:SqlSessionTemplate
	private SqlSessionTemplate sqlSession;
	public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}

	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}

	@Override
	public List<User> getUserList(User user) {
		
		return sqlSession.selectList("com.oupeng.dao.UserMapper.getUserList",user);
	}

	@Override
	public int add(User user) {
		
		return sqlSession.insert("com.oupeng.dao.UserMapper.add",user);
	}

}

6 创建业务逻辑层接口

package com.oupeng.service;

import java.util.List;

import com.oupeng.pojo.User;

public interface UserService {
	//查询所有用户
	public List<User> findUserList(User user);
	
	//插入用户
	public boolean addNewUser(User user);
}

7 创建业务逻辑层实现类

package com.oupeng.service.impl;

import java.util.List;

import com.oupeng.dao.UserMapper;
import com.oupeng.pojo.User;
import com.oupeng.service.UserService;

public class UserServiceImpl implements UserService {

	//注入数据访问层依赖(写接口松耦合,面向接口编程)
	private UserMapper userMapper;
	
	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public List<User> findUserList(User user) {
		
		return userMapper.getUserList(user);
	}

	@Override
	public boolean addNewUser(User user) {
	    int result=userMapper.add(user);
		return result>0;
	}

}

8 配置

  • MyBatis-config.xml
<?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 type="com.oupeng.pojo.User" alias="User"/> -->
		<package name="com.oupeng.pojo" />
	</typeAliases>
	
</configuration>
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

<!-- 配置数据源 -->
<bean id="dataSource"
	class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url"
		value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&amp;characterEncoding=utf-8"></property>
	<property name="username" value="root"></property>
	<property name="password" value="root"></property>
</bean>


	<!-- 配置SqlSessionFactory -->
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 加载数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 加载MyBatis的配置文件 -->
		<property name="configLocation"
			value="classpath:mybatis-config.xml"></property>
		<!--加载Mybatis的映射文件 -->
		<property name="mapperLocations">
			<!-- <value>classpath:com/oupeng/dao/UserMapper.xml</value> -->
			<!-- <value>classpath:com/oupeng/dao/ProviderMapper.xml</value> <value>classpath:com/oupeng/dao/BillMapper.xml</value> -->
			<!-- 通配符加载 -->
			<value>classpath:com/oupeng/**/*.xml</value>
		</property>
	</bean>


<!-- 配置sqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 构造注入sqlSessionFactory -->
 <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
</bean>


<!-- 配置数据访问层组件 -->
<bean id="userMapper" class="com.oupeng.dao.impl.UserMapperImpl">
<!-- 注入sqlSessionTemplate  -->
<property name="sqlSession" ref="sqlSessionTemplate"></property>
</bean>


<!-- 配置数据访问层组件 -->
<bean id="userService" class="com.oupeng.service.impl.UserServiceImpl">
<!-- 完成数据访问层对象的注入 -->
<property name="userMapper" ref="userMapper"></property>
</bean>

</beans>

11测试

package com.oupeng.test;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.oupeng.pojo.User;
import com.oupeng.service.UserService;

public class TestMybatisSpring {
        @Test
        public void test1() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            List<User> list=new ArrayList();
            UserService us=(UserService) context.getBean("userService");

    		User user=new User();
    		user.setUserName("赵");
    		user.setUserRole(2);
    		
    		list=us.findUserList(user);
    	
    		for(User u:list){
    			System.out.println(u.getUserCode()+"\t"+u.getUserName()+"\t"+u.getAddress()+"\t"+u.getUserRoleName());
    		}
        }
        
        
        @Test
        public void test2() {
        	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService us=(UserService) context.getBean("userService");
            User user=new User();
    		user.setUserCode("01245");
    		user.setUserName("曹丕");
    		user.setUserRole(2);
    		user.setAddress("雍凉");
    		user.setGender(1);
    		if(us.addNewUser(user)){
    			System.out.println("success...");
    		}else{
    			System.out.println("fail...");
    			
    		}
        }
}

执行结果

zhaomin	赵敏	北京市昌平区天通苑312号楼	经理
success...

Spring整合MyBatis 优化:

如果接口大量声明和应用,那么数据访问接口的实现类将大量上升,配置文件配置也将大量上升,开发效率受到影响,配置文件可阅读性越来越差
自动生成实现类,避免了编写大量的数据访问实现类
用userMapperProxy换essionTemplate和数据访问层组件

<!-- 指定包下所有接口主动实现配置,配置要生成实现类的接口 -->
<bean id="userMapperProxy" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.oupeng.dao.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>

</bean>

<!-- 配置业务逻辑层组件 -->
<bean id="userService" class="com.oupeng.service.impl.UserServiceImpl">
<!-- 完成数据访问层对象的注入 -->
<!-- <property name="userMapper" ref="userMapper"></property> -->
<property name="userMapper" ref="userMapperProxy"></property>
</bean>

业务逻辑层采用注解、数据访问层采用自动扫描

<!-- 自动扫描这个包下所有接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.oupeng.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!--配置让其自动扫码指定的包下的注解  -->
	<context:component-scan base-package="com.oupeng.service.impl"></context:component-scan>

注解

package com.oupeng.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.oupeng.dao.UserMapper;
import com.oupeng.pojo.User;
import com.oupeng.service.UserService;
@Service("userService1")
public class UserServiceImpl implements UserService {

	//注入数据访问层依赖(写接口松耦合,面向接口编程)
	@Autowired
	private UserMapper userMapper;
	
	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public List<User> findUserList(User user) {
		
		return userMapper.getUserList(user);
	}

	@Override
	public boolean addNewUser(User user) {
	    int result=userMapper.add(user);
		return result>0;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值