1. 程式人生 > >Spring整合MyBatis (使用掃描包配置mapper代理)

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

4.0 ike 生日 exce ini idl XML lis address

Spring整合MyBatis (使用掃描包配置mapper代理)
pojo是根據表生成的實體類,屬性名要跟字段名相同,不相同sql語句查詢時用別名。
首先導jar包

實體類

public class User {
    private Integer id;
    private String username;// 用戶姓名
    private String sex;// 性別
    private Date birthday;// 生日
    private String address;// 地址
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

第一步:
編寫MyBatis配置文件SqlMapConfig.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>
</configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

第二步:
編寫Spring 配置文件applicationContext.xml

(
db.properties:文件裏面放的是連接數據庫的相關信息。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/t003?characterEncoding=utf-8
jdbc.username=test01
jdbc.password=
)   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
<?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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

第四步編寫接口相對應的xml文件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">
<!-- 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

最後測試

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);
    }
}

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