Spring整合MyBatis (使用扫描包配置mapper代理)

来源:互联网 发布:监控员工电脑软件 编辑:程序博客网 时间:2024/06/05 09:25

Spring整合MyBatis (使用扫描包配置mapper代理)
pojo是根据表生成的实体类,属性名要跟字段名相同,不相同sql语句查询时用别名。
首先导jar包

实体类

public class User {    private Integer id;    private String username;// 用户姓名    private String sex;// 性别    private Date birthday;// 生日    private String address;// 地址}

第一步:
编写MyBatis配置文件SqlMapConfig.xml(虽然里面可以什么也不写除了头,但是必须有)。

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration></configuration>

第二步:
编写Spring 配置文件applicationContext.xml

(db.properties:文件里面放的是连接数据库的相关信息。jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/t003?characterEncoding=utf-8jdbc.username=test01jdbc.password=)   
<?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:db.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>    <!-- sqlSessonFactory的配置 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!-- 配置数据库连接池 -->        <property name="dataSource" ref="dataSource"></property>        <!-- 加载配置文件 -->        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>    </bean>    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >        <property name="basePackage" value="cn.test" />     </bean></beans>

第四步编写接口相对应的xml文件UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace是命名空间,作用sql语句的隔离,后面还有重要作用 #{}作用就是占位符,相当于jdbc的“?” parameterType:查询的参数类型     resultType:查询结果的数据类型,如果给pojo应该给全路径。 --><!-- mapper代理的开发规则: 1、namespace必须时候接口的全限定名 2、Statementid必须和接口的方法名称一致 3、接口方法的参数类型要和parameterType要一致     4、接口方法的返回值类型要和resultType一致 --><mapper namespace="cn.test.mybatis.po.UserMapper">    <!-- 别名不区分大小写 -->    <select id="getUserById" parameterType="int" resultType="cn.test.mybatis.po.User">        SELECT * FROM `user` WHERE id=#{id};    </select>    <!-- 如果查询结果返回list, resultType设置为list中一个元素的数据类型 ${}字符串拼接指令 -->    <select id="getUserByName" parameterType="string"        resultType="cn.test.mybatis.po.User">        SELECT * FROM `user` WHERE username LIKE '%${value}%'    </select>    <!--  美丽的分界线 只测试最简单的上边两个方法  -->    <!-- 参数为pojo时,#{}中的名称就是pojo的属性 -->    <!-- <insert id="insertUser" parameterType="cn.test.mybatis.po.User">        keyProperty:对于pojo的主键属性 resultType:对应主键的数据类型 order:是在insert语句执行之前或者之后。             如果使用uuid做主键,应该先生成主键然后插入数据,此时应该使用Before        <selectKey keyProperty="id" resultType="int" order="AFTER">            SELECT LAST_INSERT_ID()        </selectKey>        INSERT into user (username,birthday,sex,address)        values (#{username}, #{birthday}, #{sex}, #{address})    </insert> -->    <!-- <select id="getUserByQueryVo" parameterType="queryvo"        resultType="user">        SELECT * FROM `user` WHERE id=#{user.id};    </select> -->    <!-- 查询用户表中的记录数 -->    <!-- <select id="getUserCount" resultType="int">        SELECT count(*) FROM `user`    </select>    <sql id="find_user_list_where">        <where>            <if test="id!=null">                and id=#{id}            </if>            <if test="username != null and username != ''">                and username like '%${username}%'            </if>        </where>    </sql>    <sql id="user_field_list">        id,username,birthday,sex,address    </sql> --><!--    <select id="findUserList" parameterType="user" resultType="user">        select        <include refid="user_field_list" />        from user        <include refid="find_user_list_where" />    </select> -->    <!-- 动态sql foreach测试 -->    <!-- <select id="findUserByIds" parameterType="queryvo" resultType="user">        SELECT        <include refid="user_field_list" />        FROM `user`        <where>            and id in(1,10,20,21,31)            <foreach collection="ids" item="id" open="and id in(" close=")"                separator=",">                #{id}            </foreach>        </where>    </select> --></mapper>

最后测试

public class MyBatisTest {    private ApplicationContext applicationContext;    @Before    public void init() throws Exception {        // 初始化spring容器        applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");    }    @Test    public void testFindUserById() {        UserMapper userMapper = applicationContext.getBean(UserMapper.class);        List<User> user = userMapper.getUserByName("王五");        for (User user2 : user) {            System.out.println(user2.getUsername());        }    }    @Test    public void test() {        UserMapper userMapper = applicationContext.getBean(UserMapper.class);        User userById = userMapper.getUserById(1);        System.out.println(userById);    }}
阅读全文
0 0