1. 程式人生 > >02 mybatis動態sql(xml方式實現單表的增刪改查)

02 mybatis動態sql(xml方式實現單表的增刪改查)

QueryVo

 

package cn.itcast.domain;

import java.io.Serializable;

import java.util.List;

public class QueryVo implements Serializable {

    private List<Integer> ids;

    public List<Integer> getIds() {

        return

ids;

    }

    public void setIds(List<Integer> ids) {

        this.ids = ids;

    }

    @Override

    public String toString() {

        return "QueryVo{"

+

                "ids=" + ids +

                '}';

    }

}

 

User.java

package cn.itcast.domain;

import

java.io.Serializable;

import java.util.Date;

/**

 *

 */

public class User implements Serializable {

  /*  private Integer id;

    private String username;

    private String address;

    private String sex;

    private Date birthday;

    public User() {

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public String getSex() {

        return sex;

    }

    public void setSex(String sex) {

        this.sex = sex;

    }

    public Date getBirthday() {

        return birthday;

    }

    public void setBirthday(Date birthday) {

        this.birthday = birthday;

    }

    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", username='" + username + '\'' +

                ", address='" + address + '\'' +

                ", sex='" + sex + '\'' +

                ", birthday=" + birthday +

                '}';

    }*/

//*************************************************************************************************************************************************************

    private Integer userId;

    private String userName;

    private String userAddress;

    private String userSex;

    private Date userBirthday;

    public Integer getUserId() {

        return userId;

    }

    public void setUserId(Integer userId) {

        this.userId = userId;

    }

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this.userName = userName;

    }

    public String getUserAddress() {

        return userAddress;

    }

    public void setUserAddress(String userAddress) {

        this.userAddress = userAddress;

    }

    public String getUserSex() {

        return userSex;

    }

    public void setUserSex(String userSex) {

        this.userSex = userSex;

    }

    public Date getUserBirthday() {

        return userBirthday;

    }

    public void setUserBirthday(Date userBirthday) {

        this.userBirthday = userBirthday;

    }

    @Override

    public String toString() {

        return "User{" +

                "userId=" + userId +

                ", userName='" + userName + '\'' +

                ", userAddress='" + userAddress + '\'' +

                ", userSex='" + userSex + '\'' +

                ", userBirthday=" + userBirthday +

                '}';

    }

    public static void main(String[] args) {

        System.out.println("000");

    }

}

 

 

IUserDao.java

package cn.itcast.dao;

import cn.itcast.domain.QueryVo;

import cn.itcast.domain.User;

import java.util.List;

/**

 * 使用者介面

 */

public interface IUserDao {

    //根據使用者資訊,查詢使用者列表

    public List<User> findUser(User user);

    //傳入多個 id 查詢使用者資訊

    public List<User> findUsersByIds(List<Integer> list);

    //傳入多個 id 查詢使用者資訊(多個id放入list,在將list作為Queryvo的屬性)

    public List<User> findUsersByIds1(QueryVo queryVo);

    //修改使用者

    public void updateUser(User user);

    //新增使用者

    public void addUser(User user);

}

 

IUserDao.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.dao.IUserDao">

    <!--配置user類的屬性和user表中的列的對應關係(主要是解決表查詢出來的欄位名和pojo的屬性名不一致)

      (type="user"是在SqlMapConfig中配置別名了,所以可以直接寫user)-->

    <resultMap id="userMap" type="user">

    <!--注意column屬性對應的是sql語句查詢出來的欄位名(或者起的別名),不是表中的欄位-->

        <!-- 主鍵欄位的對應 -->

        <id property="userId" column="id"></id>

        <!--非主鍵欄位的對應-->

        <result property="userName" column="username"></result>

        <result property="userAddress" column="address"></result>

        <result property="userSex" column="sex"></result>

        <result property="userBirthday" column="birthday"></result>

    </resultMap>

    <!--抽取sql片段-->

    <sql id="user_sql">

        select * from user

    </sql>

    <!--根據使用者資訊,查詢使用者列表

     parameterType:引數型別

     resultMap:對應<resultMap>標籤的id 

     -->

    <select id="findUser" parameterType="user" resultMap="userMap">

        <!--引用sql片段-->

        <include refid="user_sql"></include>

        <where>

            <if test="userName != null and userName != '' ">

                username = #{userName}

            </if>

            <if test="userSex != null and userSex != '' ">

                and sex = #{userSex}

            </if>

        </where>

    </select>

    <!--傳入多個 id 查詢使用者資訊(多個id放入list),如果採用這種做法,引數只能寫 list 不推薦-->

   <!--foreach

        collection:需要遍歷的集合

        item:每次遍歷的物件

        open:迴圈開始輸出的內容,只會輸出一次

        close:迴圈結束輸出的內容,只會輸出一次

        separator:每次迴圈後,新增的內容,迴圈幾次新增幾次

             -->

    <select id="findUsersByIds" parameterType="java.util.List" resultMap="userMap">

        <!--引用sql片段-->

        <include refid="user_sql"></include>

        <!--select * from user where id in(42,43,45)-->

        <where>

            <if test="list != null and list.size() > 0">

                <foreach collection="list" item="id" open="id in  (" close=")" separator=",">

                    #{id}

                </foreach>

            </if>

        </where>

    </select>

    <!--傳入多個 id 查詢使用者資訊(多個id放入list,在將list作為Queryvo的屬性)-->

    <!--使用這種sql語句進行查詢select * from user where id in(42,43,45)-->

    <!--<select id="findUsersByIds1" parameterType="cn.itcast.domain.QueryVo" resultMap="userMap">

        <include refid="user_sql"></include>

        <where>

            <if test="ids != null and ids.size()>0">

                <foreach collection="ids" item="id" open="id in (" close=")" separator=",">

                    #{id}

                </foreach>

            </if>

        </where>

    </select>-->

    <!--傳入多個 id 查詢使用者資訊(多個id放入list,在將list作為Queryvo的屬性)-->

    <!--使用這種sql語句進行查詢select * from user where id = 42 or id = 43 or id = 45-->

    <select id="findUsersByIds1" parameterType="cn.itcast.domain.QueryVo" resultMap="userMap">

        <include refid="user_sql"></include>

        <where>

            <if test="ids != null and ids.size()>0">

                <foreach collection="ids" item="id" separator="or">

                    id = #{id}

                </foreach>

            </if>

        </where>

    </select>

    <!--修改使用者  update user set sex = ?,username = ? where id = ?-->

    <update id="updateUser" parameterType="user">

        update user

        <set>

            <if test="userSex != null and userSex != '' ">

                sex = #{userSex},

            </if>

            <if test="userName != null and userName != '' ">

                username = #{userName}

            </if>

        </set>

        <where>

            <if test="userId != null and userId != '' ">

                id = #{userId}

            </if>

        </where>

    </update>

    <!--新增使用者   insert into user (username,birthday,sex,address) VALUES(?,?,?,?)-->

    <insert id="addUser" parameterType="user">

        <!--新增成功之後,返回id-->

        <!--selectKey作用:

                   獲取新增物件的id

                   order:在新增之後執行用(BEFORE),新增之前用(AFTER

                   mysql:自增,last_insert_id()  AFTER  ====>在新增成功之後,返回新增那條的id

                   UUID   uuid(); 一般在新增之前進行uuid的插入

                   resultType:返回主鍵ID的型別

                   keyProperty:模型類中主鍵的屬性名

                   order:新增之前,還是新增之後

        -->

        <selectKey resultType="java.lang.Integer" keyProperty="userId" order="AFTER">

            select last_insert_id()

            <!--select uuid()-->

        </selectKey>

        insert into user (<include refid="insert_key"></include>) VALUES(<include refid="insert_value"></include>)

    </insert>

    <!--

    <trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>

    prefix:trim標籤內sql語句加上字首。

    suffix:trim標籤內sql語句加上字尾。

    suffixOverrides:指定去除多餘的字尾內容,如:suffixOverrides=",",去除trim標籤內sql語句多餘的字尾","

    prefixOverrides:指定去除多餘的字首內容

        userNameuserBirthday,userAddress為pojo屬性名

   username,birthday,address,為資料庫欄位名

    -->

    <sql id="insert_key">

        <trim suffixOverrides=",">

            <if test="userName != null and userName != '' ">

                username,

            </if>

            <if test="userBirthday != null">

                birthday,

            </if>

            <if test="userSex != null and userSex != '' ">

                sex,

            </if>

            <if test="userAddress != null and userAddress != '' ">

                address,

            </if>

        </trim>

    </sql>

    <sql id="insert_value">

        <trim suffixOverrides=",">

            <if test="userName != null and userName != '' ">

                #{userName},

            </if>

            <if test="userBirthday != null">

                #{userBirthday},

            </if>

            <if test="userSex != null and userSex != '' ">

                #{userSex},

            </if>

            <if test="userAddress != null and userAddress != '' ">

                #{userAddress},

            </if>

        </trim>

    </sql>

</mapper>

 

MybatisTest.java

 

package test;

import cn.itcast.dao.IUserDao;

import cn.itcast.domain.QueryVo;

import cn.itcast.domain.User;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import java.io.IOException;

import java.io.InputStream;

import java.text.ParseException;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

public class MybatisTest {

    private InputStream in;

    private IUserDao userDao;

    private SqlSession sqlSession;

    //在測試方法之前執行

    @Before

    public void init() {

        /**

         * ORM+SqlMapConfig+sqlSession

         */

        //載入配置檔案

        in = MybatisTest.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        //建立構建者物件

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        //建立sqlSession工廠

        SqlSessionFactory sqlSessionFactory = builder.build(in);

        //建立sqlSession

        sqlSession = sqlSessionFactory.openSession();

        //獲取代理物件

        userDao = sqlSession.getMapper(IUserDao.class);

    }

    //測試方法之後執行

    @After

    public void destory() throws IOException {

        //提交事務

        sqlSession.commit();

        //釋放資源

        sqlSession.close();

        in.close();

    }

    //根據使用者資訊,查詢使用者列表

    @Test

    public void testFindUser() {

        User user = new User();

        user.setUserName("李四");

        user.setUserSex("");

        List<User> list = userDao.findUser(user);

        for (User user1 : list) {

            System.out.println(user1);

        }

    }

    //傳入多個 id 查詢使用者資訊(多個id放入list)

    @Test

    public void testFindUsersByIds() {

        List<Integer> ids = new ArrayList<Integer>();

        ids.add(42);

        ids.add(45);

        List<User> list1 = userDao.findUsersByIds(ids);

        for (User user1 : list1) {

            System.out.println(user1);

        }

    }

    //傳入多個 id 查詢使用者資訊(多個id放入list,在將list作為Queryvo的屬性)

    @Test

    public void testFindUsersByIds1() {

        List<Integer> list = new ArrayList<Integer>();

        list.add(42);

        list.add(43);

        list.add(45);

        QueryVo queryVo = new QueryVo();

        queryVo.setIds(list);

        List<User> userList = userDao.findUsersByIds1(queryVo);

        for (User user : userList) {

            System.out.println(user);

        }

    }

    //修改id42的使用者的性別為男,地址為中國

    @Test

    public void testUpdateUser(){

        User user = new User();

        user.setUserSex("");

        user.setUserName("韓曉峰");

        user.setUserId(43);

        userDao.updateUser(user);

    }

    //新增使用者

    @Test

    public void testAddUser() throws ParseException {

        User user = new User();

        user.setUserName("張瑩瑩");

        user.setUserAddress("陝西咸陽");

        user.setUserSex("");

        Date date = new Date();

        user.setUserBirthday(date);

        userDao.addUser(user);

    }

}

db.properties

 

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/mybatis

jdbc.username=root

jdbc.password=123456

 

log4j.properties

 

此檔案可以輸出到檔案

 

 

# Set root category priority to INFO and its only appender to CONSOLE.

#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal

 

 

#輸出到log檔案中(d:\axis.log檔案中)

#log4j.rootCategory=debug, CONSOLE, LOGFILE

#只輸出到控制檯

log4j.rootCategory=debug, CONSOLE

 

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.

log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

 

# 日誌輸出到控制檯

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

 

# 日誌輸出到指定檔案,根路徑/

log4j.appender.LOGFILE=org.apache.log4j.FileAppender

log4j.appender.LOGFILE.File=/axis.log

log4j.appender.LOGFILE.Append=true

log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout

log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

 

 

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>

    <!--配置properties 1.可以在標籤內部配置連線資料庫的資訊。

                       2.也可以通過屬性引用外部配置檔案資訊,url屬性或者resource屬性

                        resource屬性: 常用的 用於指定配置檔案的位置,是按照類路徑的寫法來寫,並且必須存在於類路徑下-->

    <!--<properties url="file:///D:/ideaProject/mybatis02/src/main/resources/db.properties" >--><!--file://這是一種檔案協議(windows)-->

    <properties resource="db.properties">

        <!--標籤內部配置資料庫連線資訊(不推薦)-->

        <!-- <property name="driver" value="com.mysql.jdbc.Driver"></property>

                    <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"></property>

                    <property name="username" value="root"></property> <property name="password"

                    value="1234"></property> -->

    </properties>

    <!--配置別名-->

    <!--使用typeAliases配置別名,它只能配置domain中類的別名 -->

    <typeAliases>

        <!--1.typeAlias用於配置別名。type屬性指定的是實體類全限定類名。alias屬性指定別名,當指定了別名就不再區分大小寫-->

        <!--<typeAlias type="cn.itcast.domain.User" alias="user"></typeAlias>-->

        <!-- 用於指定要配置別名的包,當指定之後,該包下的實體類都會註冊別名,並且類名就是別名,不再區分大小寫 -->

        <package name="cn.itcast.domain"></package>

    </typeAliases>

    <!-- 配置 mybatis 的環境 -->

    <environments default="mysql">

        <environment id="mysql">

            <!-- 配置事務的型別 -->

            <transactionManager type="JDBC"/>

            <!-- 配置連線資料庫的資訊:用的是資料來源(連線池) -->

            <dataSource type="POOLED">

                <property name="driver" value="${jdbc.driver}"/>

                <property name="url" value="${jdbc.url}"/>

      &nbs