Spring整合mybatis

1.需要整合的jar包

  1. spring的jar包
  2. Mybatis的jar包
  3. Spring+mybatis的整合包。
  4. Mysql的数据库驱动jar包。
  5. 数据库连接池的jar包。

2.配置 SqlMapConfig.xml

mybatis主配置文件会内容交由spring管理

<?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>
	
	<!-- 加载映射文件 -->
	<mappers>
	
	<mapper resource="User.xml"/>
	<!-- 
	class: 加载动态代理开发方式的接口
	接口和实体类除拓展名以外 ,命名必须一致
	 -->
	
<!-- <package name="cn.itcast.mapper"/>  -->
	</mappers>
	
</configuration>

3.配置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: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/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>
	<!-- 配置 会话工厂-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 配置使用的mybatis核心配置文件位置 -->
	<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
	<!-- 配置使用的数据源 -->
	<property name="dataSource" ref="dataSource"></property>
	
	</bean>
	<!-- 原生Dao开发方式 -->
	<bean id="userDao" class="cn.huitong.dao.UserDaoImpl">
		<!-- 配置使用的会话工厂 -->
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
	
	
	<!--动态代理包扫描的方式配置,实例化的时加载包下面的接口,可以使用接口名加载  -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 配置扫描的包 -->
	<property name="basePackage" value="cn.huitong.mapper"></property>
	
	</bean>
</beans>	

原生dao开发方式

原生dao开发方式接口实现类需继承SqlSessionDaoSupport

applicationContext.xml配置

</bean>
	<!-- 原生Dao开发方式 -->
	<bean id="userDao" class="cn.huitong.dao.UserDaoImpl">
		<!-- 配置使用的会话工厂 -->
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>

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 命名空间
当调用时   命名空间.方法名
parameterType  定义输入到sql中的参数映射类型
resultType  定义返回结果映射类型
#{} 占位符 ,当#{}里为基本类型时 可以任意命名占位#{xxx}    #{}可以有效防止sql注入
-->
<mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="cn.huitong.pojo.User">
select * from user where id = #{id}
</select>

<!--
${} 占位符 ,只有模糊查询会用到,如果是取简单数量类型的参数,括号中的值必须为value
  -->
<select id="findUserByName" parameterType="string" resultType="cn.huitong.pojo.User">
select * from user where  username like '%${value}%'
</select>
<!-- 
添加一个对象,传入的参数有多个 ,用pojo实体类封装,占位符内变量名必须与实体类属性名一致
 -->
<insert id="insertUser" parameterType="cn.huitong.pojo.User">
<!-- 
select LAST_INSERT_ID()   查询最后一条插入数据库数据id
keyProperty 将查询出来的id封装到实体类user id属性中
order 在insert语句  之前或者之后执行  (before之前  after 之后)
resultType 返回结果类型
 -->
<selectKey keyProperty="id" order="AFTER" resultType="int">
select LAST_INSERT_ID()
</selectKey>
 insert into user (username,birthday, sex, address) values(#{username},#{birthday},#{sex},#{address})
 </insert>
<delete id="deleteFindById" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="updateUser" parameterType="cn.huitong.pojo.User" >
update user set username=#{username} where id=#{id}
</update>
</mapper>

dao接口 

public interface UserDao {
	public User findUserById( int id);
	public List<User>findUserByName(String username);
}

接口实现类

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

	@Override
	public User findUserById(int id) {
		SqlSession openSession = this.getSqlSession();
		User user = openSession.selectOne("test.findUserById", id);
		return user;
	}

	@Override
	public List<User> findUserByName(String username) {
		SqlSession openSession = this.getSqlSession();
		List<User> userList = openSession.selectList("test.findUserByName", username);
		return userList;
	}

	

}

测试

public class UserDaoTest {
	//Spring核心接口,spring环境信息对象
private ApplicationContext applicationContext;
	
	@Before 
	public void createSqlSessionFactory() throws IOException{
		//读取配置文件
		applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		
	}
	
	//根据id查询
	@Test
	public void findUserById(){
		//获取实例化对象
	UserDao userDao=(UserDao) applicationContext.getBean("userDao");
	
	User user = userDao.findUserById(28);
	System.out.println(user);
	}
	//根据姓名模糊查询
	@Test
	public void findUserByName(){
	//获取实例化对象
	UserDao userDao=(UserDao) applicationContext.getBean("userDao");
	List<User> userList = userDao.findUserByName("王");
	System.out.println(userList);
	}
	
}

动态代理形式开发dao

applicationContext.xml配置

<!--动态代理包扫描的方式配置,实例化的时加载包下面的接口,可以使用接口名加载  -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 配置扫描的包 -->
	<property name="basePackage" value="cn.huitong.mapper"></property>
	</bean>

逆向工程生成代码

UserMapper.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" >
<mapper namespace="cn.itcast.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="cn.itcast.pojo.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="birthday" property="birthday" jdbcType="DATE" />
    <result column="sex" property="sex" jdbcType="CHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>

dao接口

public interface UserMapper {
    int countByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    List<User> selectByExample(UserExample example);

    User selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

测试

public class UserMapperTest {

private ApplicationContext  applicationContext;
	
	@Before  
	public void createSqlSessionFactory() throws IOException{
		applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	//逆向工程导入    根据id查询
	@Test
	public void findUserById(){
		//通过接口名加载获取接口实例化对象
		UserMapper mapper=(UserMapper) applicationContext.getBean("userMapper");
		//调用方法
		User user = mapper.selectByPrimaryKey(28);
		System.out.println(user);
	}
	

	//逆向工程导入    查询所有
	@Test
	public void findAll(){
		//通过接口名加载获取接口实例化对象
		UserMapper mapper=(UserMapper) applicationContext.getBean("userMapper");
		//调用方法  selectByExample 根据条件查询 ,条件为空,查询所有
		List<User> user = mapper.selectByExample(null);
		System.out.println(user);
	}
	
	//逆向工程导入  条件查询
	@Test
	public void findUserByNameAndSex(){
	//通过接口名加载获取接口实例化对象
	UserMapper mapper=(UserMapper) applicationContext.getBean("userMapper");
	//创建查询对象  UserExample 
	UserExample userExample=new UserExample();
	//创建sql语句中where条件
	Criteria createCriteria = userExample.createCriteria();
	createCriteria.andSexEqualTo("1");
	createCriteria.andUsernameLike("%白%");
	//根据条件查询
	List<User> user = mapper.selectByExample(userExample);
	System.out.println(user);
	}
	

 UserMapper mapper=(UserMapper) applicationContext.getBean("userMapper");

动态代理包扫描的方式配置, 实例化的时候, 加载包下面的接口, 可以使用接口名加载 ("userMapper")

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值