19 JAVA study notes - Chapter MyBatis framework

Please indicate the source: http://blog.csdn.net/woshizisezise/article/details/78796228

Then yesterday MyBatis entry procedures is concerned, today we are speaking about MyBatis advanced uses, such as dynamic sql queries related inquiries, integrated Spring framework, we want to be able to help.


1, dynamic sql

Tag by various methods of providing dynamic splicing mybatis sql.

1.1 if the label

<!-- 传递pojo综合查询用户信息 -->
<select id="findUserList" parameterType="user" resultType="user">
    select * from user 
    where 1=1 
    <if test="id!=null">
        and id=#{id}
    </if>
    <if test="username!=null and username!=''">
        and username like '%${username}%'
    </if>
</select>

Note that do not equal an empty string check.

1.2 where labels

Top of the sql can also read:

<select id="findUserList" parameterType="user" resultType="user">
    select * from user 
    <where>
        <if test="id!=null and id!=''">
            and id=#{id}
        </if>
        <if test="username!=null and username!=''">
            and username like '%${username}%'
        </if>
    </where>
</select>

<where />It can automatically process the first and.

1.3 foreach tag

Sql transmitted to an array or List, mybatis foreach analytical use, as follows:

  • demand

Incoming queries multiple user id information, implemented in the following two sql:

SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE '%张%'  id IN (10,89,16)
  • In pojo ids defined attribute list storing a plurality of user id, and add getter / setter methods
public class QueryVo{
    private User user;

    //自定义用户扩展类
    private UserCustom userCustom;

    //传递多个用户id
    private List<Integer> ids;
}
  • In pojo ids defined attribute list storing a plurality of user id, and add getter / setter methods
<if test="ids!=null and ids.size>0">
     <foreach collection="ids" open=" and id in(" close=")" item="id" separator="," >
                #{id}
     </foreach>
</if>
  • Test code:
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);//查询id为1的用户
ids.add(10); //查询id为10的用户
queryVo.setIds(ids);
List<User> list = userMapper.findUserList(queryVo);

1.4 Sql fragment

Sql can duplicate sql extracted, with reference to include the use of, and ultimately to sql reuse, as follows:

<!-- 传递pojo综合查询用户信息 -->
<select id="findUserList" parameterType="user" resultType="user">
    select * from user 
    <where>
    <if test="id!=null and id!=''">
    and id=#{id}
    </if>
    <if test="username!=null and username!=''">
    and username like '%${username}%'
    </if>
    </where>
</select>
  • Where conditions will be extracted:
<sql id="query_user_where">
    <if test="id!=null and id!=''">
        and id=#{id}
    </if>
    <if test="username!=null and username!=''">
        and username like '%${username}%'
    </if>
</sql>
  • Use references include:
<select id="findUserList" parameterType="user" resultType="user">
    select * from user 
    <where>
        <include refid="query_user_where"/>
    </where>
</select>

Note: If the reference segment sql mapper.xml the other, when you need to add namespace references as follows:

<include refid="namespace.sql片段”/>

2. Related Queries

2.1 one-inquiry

Case: All order information query, the query associated with the single-user information.

Note: Because an order information will only be under the orders of a man, so the starting order information from query to query the user information related to one query. If the user information from the order information in the user query, compared to many queries because a user can place multiple orders.

method one

Using the resultType, po order information defined class, this class includes po order information and the user information:

2.1.1.1 sql statement
SELECT 
  orders.*,
  user.username,
  user.address
FROM
  orders,
  user 
WHERE orders.user_id = user.id
2.1.1.2 class definitions po

Po category should include all the fields out of the top sql query, as follows:

public class OrdersCustom extends Orders {

    private String username;// 用户名称
    private String address;// 用户地址
    get/set......
}

After OrdersCustom class inherits Orders class OrdersCustom category includes all the fields from the Orders class, only need to define user information fields can be.

2.1.1.3 mapper.xml file
<!-- 查询所有订单信息 -->
<select id="findOrdersList" resultType="cn.zy.mybatis.po.OrdersCustom">
    SELECT orders.*,user.username,user.address
    FROM orders,user
    WHERE orders.user_id = user.id 
</select>
2.1.1.4 mapper interface definition
public List<OrdersCustom> findOrdersList() throws Exception;
2.1.1.5 Test
Public void testfindOrdersList()throws Exception{
    //获取session
    SqlSession session = sqlSessionFactory.openSession();
    //获限mapper接口实例
    UserMapper userMapper = session.getMapper(UserMapper.class);
    //查询订单信息
    List<OrdersCustom> list = userMapper.findOrdersList();
    System.out.println(list);
    //关闭session
    session.close();
}
2.1.1.6 Summary

Po specialized class as defined output type, which defines the set of all sql query result fields. This method is simple, general business use.

Method Two

Use resultMap, the definition of special resultMap used to map one to one query results.

2.1.2.1 sql statement
SELECT 
  orders.*,
  user.username,
  user.address
FROM
  orders,
  user 
WHERE orders.user_id = user.id
2.1.2.2 class definitions po

User added Orders class attribute, user attribute for the user to store information associated with the query, because the orders associated with user queries are one to one relationship, so where user information is stored associated with a single User object query.

public class Orders{
    private Integer id;
    private Integer userId;
    private String number;
    private Date createtime;
    private String note;
    private User user;

    getter()、setter()方法......
}
2.1.2.3 mapper.xml file
<!-- 查询订单关联用户信息使用resultmap -->
<resultMap type="cn.itheima.po.Orders" id="orderUserResultMap">
    <id column="id" property="id"/>
    <result column="user_id" property="userId"/>
    <result column="number" property="number"/>
    <result column="createtime" property="createtime"/>
    <result column="note" property="note"/>
    <!-- 一对一关联映射 -->
    <!-- 
        property:Orders对象的user属性
        javaType:user属性对应 的类型
     -->
    <association property="user" javaType="cn.itcast.po.User">
        <!-- column:user表的主键对应的列  property:user对象中id属性-->
        <id column="user_id" property="id"/>
        <result column="username" property="username"/>
        <result column="address" property="address"/>
    </association>
</resultMap>
<select id="findOrdersWithUserResultMap" resultMap="orderUserResultMap">
    SELECT
        o.id,
        o.user_id,
        o.number,
        o.createtime,
        o.note,
        u.username,
        u.address
    FROM
        orders o
    JOIN `user` u ON u.id = o.user_id
</select>

Here resultMap specified orderUserResultMap.

association: associating a query indicates a single record
property: The results are stored in the user attribute associated with the query in cn.itcast.mybatis.po.Orders
javaType: shows the result type associated with the query
<id property="id" column="user_id"/>: id attribute query result user_id column association objects here is a user_id is a unique identifier associated with the query object.
<result property="username" column="username"/>: Query result username column corresponds username attributes associated with the object.

2.1.2.4 mapper Interface
public List<Orders> findOrdersListResultMap() throws Exception;
2.1.2.5 Test
Public void testfindOrdersListResultMap()throws Exception{
    //获取session
    SqlSession session = sqlSessionFactory.openSession();
    //获限mapper接口实例
    UserMapper userMapper = session.getMapper(UserMapper.class);
    //查询订单信息
    List<Orders> list = userMapper.findOrdersWithUserResultMap();
    System.out.println(list);
    //关闭session
    session.close();
}
2.1.2.6 Summary

Use association to complete association query, map query information related to pojo object.


2.2-to-many query

Case: check your order information and user information associated with the user at all.

User information and order information to many relationship.

Use resultMap achieve the following:

2.2.1 sql statement
SELECT
    u.*, o.id oid,
    o.number,
    o.createtime,
    o.note
FROM
    `user` u
LEFT JOIN orders o ON u.id = o.user_id
2.2.2 class definitions po

Was added to the User class List<Orders> ordersattributes

public class User{
    private Integer id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;
    private List<Orders> orders;

    getter()、setter()方法......
}
2.2.3 mapper.xml
<resultMap type="cn.itheima.po.user" id="userOrderResultMap">
    <!-- 用户信息映射 -->
    <id property="id" column="id"/>
    <result property="username" column="username"/>
    <result property="birthday" column="birthday"/>
    <result property="sex" column="sex"/>
    <result property="address" column="address"/>
    <!-- 一对多关联映射 -->
    <collection property="orders" ofType="cn.itheima.po.Orders">
        <id property="id" column="oid"/>    
          <!--用户id已经在user对象中存在,此处可以不设置-->
        <!-- <result property="userId" column="id"/> -->
        <result property="number" column="number"/>
        <result property="createtime" column="createtime"/>
        <result property="note" column="note"/>
    </collection>
</resultMap>
<select id="getUserOrderList" resultMap="userOrderResultMap">
    SELECT
        u.*, o.id oid,
        o.number,
        o.createtime,
        o.note
    FROM
        `user` u
    LEFT JOIN orders o ON u.id = o.user_id
</select>

collection section defines the order information associated with the user. Indicates that the associated query result set
property = "orders": on which property associated with the query result set is stored in the User object.
ofType = "orders": the results of the query associated with the specified object type that is focused on the object type List. Here you can use an alias, you can also use the fully qualified name.
<id />And <result/>meaning with one query.

2.2.4 mapper Interface
List<User> getUserOrderList();
2.2.5 Testing
@Test
public void getUserOrderList() {
    SqlSession session = sqlSessionFactory.openSession();
    UserMapper userMapper = session.getMapper(UserMapper.class);
    List<User> result = userMapper.getUserOrderList();
    for (User user : result) {
        System.out.println(user);
    }
    session.close();
}

3, Mybatis integrated spring

3.1 impoundment

1, SqlSessionFactory objects should be placed in the container as a single spring present embodiment.
2, the traditional development dao, the subject should be obtained from the spring sqlsession container.
3, Mapper proxy form should be obtained directly from the proxy object mapper spring vessel.
4, database connection and transaction management database connection pool are to spring container to complete.


3.2 Integration requires jar package

1, spring jar package
2, Mybatis jar package
3, Spring + mybatis integrated package.
4, Mysql database driver jar package.
5, the database connection pool jar package.


3.3 Integration steps

Step 1: Create a java project.
Step Two: Import jar package. (Above mentioned jar package)
The third step: MyBatis profile sqlmapConfig.xml
fourth step: preparation of Spring profile
1, and connected to the database connection pool
2, transaction management (temporarily may not be arranged)
. 3, SqlSessionFactory objects, spring configured into vessel
4, mapeer proxy object implementation class or dao spring disposed to a container.
Step five: Write dao or mapper file
Step Six: Testing.

  • 3.3.1 write SqlMapConfig.xml profile
<?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>
        <package name="cn.itcast.mybatis.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
    </mappers>
</configuration>
  • 3.3.2 write applicationContext.xml profile
<?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>
    <!-- mapper配置 -->
    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
    </bean>
</beans>
  • 3.3.3 write the configuration file database db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

Development 3.4 Dao layer

Dao three kinds of ways:
1. Traditional dao development mode
2, the mapper proxy form development mode
3, the mapper proxy scanning package configuration.

3.4.1 dao traditional development mode

To complete the interface and implementation class. Need dao implementation class needs to inherit SqlsessionDaoSupport class.

3.4.1.1 Dao implementation class
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

    @Override
    public User findUserById(int id) throws Exception {
        SqlSession session = getSqlSession();
        User user = session.selectOne("test.findUserById", id);
        //不能关闭SqlSession,让spring容器来完成
        //session.close();
        return user;
    }

    @Override
    public void insertUser(User user) throws Exception {
        SqlSession session = getSqlSession();
        session.insert("test.insertUser", user);
        session.commit();
        //session.close();
    }

}
3.4.1.2 Configuration Dao

The implementation class dao spring arranged to vessel

<!-- 配置UserDao实现类 -->
<bean id="userDao" class="cn.zy.dao.UserDaoImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
3.4.1.3 Test Method

initialization:

private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception{
    String configLocation = "classpath:spring/ApplicationContext.xml";
    //初始化spring运行环境
    applicationContext = new ClassPathXmlApplicationContext(configLocation);
}

test:

@Test
public void testFindUserById() throws Exception {
    UserDao userDao = (UserDao) applicationContext.getBean("userDao");
    User user = userDao.findUserById(1);
    System.out.println(user);
}

3.4.2 Mapper proxy form development dao

3.4.2.1 Development mapper interfaces

Write mapper interfaces, note the name of the interface method needs and mapper.xml profile id of the same name.

3.4.2.2 mapper proxy configuration
<!-- 配置mapper代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="cn.zy.mybatis.mapper.UserMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
3.4.2.3 Test Method
public class UserMapperTest {

    private ApplicationContext applicationContext;
    @Before
    public void setUp() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }

    @Test
    public void testGetUserById() {
        UserMapper userMapper = applicationContext.getBean(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);
    }
}

3.4.3 scan packages in the form of the mapper

<!-- 使用扫描包的形式来创建mapper代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.zy.mybatis.mapper"/>
</bean>

Each id mapper proxy object is the class name, the first letter lowercase


ok, wrote last, today's article about Advanced use MyBatis has finished, supposedly written should be regarded as steps in detail, concise, and we want to help slightly, have any questions you can leave a message if I would then we will discuss and, if you have the wrong place, welcome to indicate correct ~

Published 87 original articles · won praise 161 · views 870 000 +

Guess you like

Origin blog.csdn.net/woshizisezise/article/details/78796228
Recommended