MyBatis入門(四)---動態SQL

MyBatis入門(四)---動態SQL

1、建立數據庫表

1.一、建立表 html

 

複製代碼
USE `mybatis`; /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用戶ID', `name` varchar(45) NOT NULL DEFAULT '無名氏' COMMENT '用戶名', `age` tinyint(3) NOT NULL DEFAULT '21' COMMENT '用戶年齡', `birthday` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '用戶生日', `address` varchar(256) NOT NULL DEFAULT '北京' COMMENT '用戶地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8 COMMENT='用戶表'; /*Data for the table `user` */ insert into `user`(`id`,`name`,`age`,`birthday`,`address`) values (1,'趙敏',23,'1990-01-23 20:24:21','明教'), (2,'李四',18,'1986-12-23 12:13:11','廣州'), (3,'張五',33,'1975-09-23 02:13:11','上海'), (4,'王六',27,'1984-11-01 11:23:14','重慶'), (5,'張三丰',108,'1971-01-02 02:12:11','武當'), (6,'想起 來叫什麼了',22,'1984-01-23 20:23:22','魔都上海'), (7,'呵呵',22,'1984-01-23 20:23:22','不知道是哪的'), (8,'張無忌',18,'2015-10-28 15:31:31','明教');
複製代碼

 

 

 

2、建立項目導入Jar包

2.一、 java

3、建立實現類和Mybatis各個配置文件  mysql

3.一、建立pojo類 sql

 

複製代碼
/** */ package com.pb.mybatis.po; import java.util.Date; /** * @Title: User.java * @Package com.pb.mybatis.po * @ClassName User * @Description: TODO(用戶類) * @author 劉楠 * @date 2015-10-30 下午4:27:05 * @version V1.0 */ public class User { //用戶ID private int id; //用戶名 private String name; //用戶年齡 private int age; //生日 private Date birthday; //地址 private String address; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the birthday */ public Date getBirthday() { return birthday; } /** * @param birthday the birthday to set */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * @return the address */ public String getAddress() { return address; } /** * @param address the address to set */ public void setAddress(String address) { this.address = address; } /** (non Javadoc) * <p>Title: toString</p> * <p>Description: </p> * @return * @see java.lang.Object#toString() */ @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + ", birthday=" + birthday + ", address=" + address + "]"; } }
複製代碼

 

3.二、建立db.properties 數據庫

 

複製代碼
#數據庫基本配置信息 #驅動 jdbc.driver=com.mysql.jdbc.Driver #鏈接URL jdbc.url=jdbc:mysql://localhost:3306/mybatis?CharacterEncoding=utf8 #用戶名 jdbc.username=root #密碼 jdbc.password=root
複製代碼

log4j apache

複製代碼
# Global logging configuration log4j.rootLogger=DEBUG, stdout # MyBatis logging configuration... # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
複製代碼

 

3.三、建立UserMapper與mapper.xml session

 

複製代碼
/** */ package com.pb.mybatis.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.pb.mybatis.po.User; /** * @Title: UserMapper.java * @Package com.pb.mybatis.mapper * @ClassName UserMapper * @Description: TODO(用戶類數據訪問層Mapper接口) * @author 劉楠 * @date 2015-10-30 下午6:17:43 * @version V1.0 */ public interface UserMapper { public User findUserById(int id); /** * * @Title: findUserByWhere * @Description: TODO(根據條件查詢用戶) * @return List<User> */ public List<User> findUserByWhere(@Param("id") int id,@Param("name")String username); /** * * @Title: updateUser * @Description: TODO(修改) * @param user * @return int */ public int updateUser(User user); }
複製代碼

xml mybatis

複製代碼
<?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="com.pb.mybatis.mapper.UserMapper">
<!-- 映射 -->

<resultMap type="User" id="userResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="birthday" column="birthday"/>
<result property="address" column="address"/>
</resultMap>


<select id="findUserById" parameterType="int" resultMap="userResultMap"> select * from user where id=#{id} </select>



<!-- 根據條件查詢用戶 -->
<select id="findUserByWhere" resultMap="userResultMap"> select * from user <where>
<!--where會自動去掉第一個成功的條件的and和or  -->
<if test="id!=null and id!='' and id!=0"> and id=#{id} </if>
<if test="name!=null and name!=''"> or name like "%"#{name}"%"
</if>
</where>
</select>


<!--修改 SET NAME=#{name}, age=#{age}, birthday=#{birthday}, address=#{address} -->
<update id="updateUser" parameterType="User"> UPDATE USER <!--使用SET來更新  -->
<set>
<if test="name !=null and name !=''">NAME=#{name},</if>
<if test="age !=null  and age !='' and age !=0">age=#{age},</if>
<if test="birthday !=null">birthday=#{birthday},</if>
<if test="address !=null and address !=''">address=#{address}</if>
</set> WHERE id=#{id} </update>

</mapper>
複製代碼

 

3.四、建立configuration.xml app

 

複製代碼
<?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 resource="db.properties" />
<typeAliases>
<!--使用默認別名  -->
<package name="com.pb.mybatis.po"/>
</typeAliases>
<environments default="development">
<environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </dataSource>
</environment>
</environments>
<mappers>
<!-- 加載映射 -->
<package name="com.pb.mybatis.mapper"/>
</mappers>
</configuration>
複製代碼

 

3.五、測試 ide

 

複製代碼
/** */ package com.pb.mybatis.mapper; import static org.junit.Assert.*; import java.io.InputStream; import java.util.Date; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.pb.mybatis.po.User; /** * @Title: UserMapperTest.java * @Package com.pb.mybatis.mapper * @ClassName UserMapperTest * @Description: TODO(用一句話描述該文件作什麼) * @author 劉楠 * @date 2015-10-30 下午6:25:23 * @version V1.0 */ public class UserMapperTest { private SqlSessionFactory sqlSessionFactory; /** * * @Title: setUp * @Description: TODO(在每一個方法前執行的方法) * @throws Exception void */ @Before public void setUp() throws Exception { String resource="configuration.xml"; InputStream in=Resources.getResourceAsStream(resource); //獲取會話工廠 sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); } @Test public void testFindUserById() { //獲取會話 SqlSession sqlSession=sqlSessionFactory.openSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); User user=userMapper.findUserById(1); System.out.println(user); } @Test public void testFindUserByWhere() { //獲取會話 SqlSession sqlSession=sqlSessionFactory.openSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); List<User> list=userMapper.findUserByWhere(0,""); System.out.println(list); } @Test public void testUpdateUser() { //獲取會話 SqlSession sqlSession=sqlSessionFactory.openSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); User user=userMapper.findUserById(6); System.out.println(user); user.setBirthday(new Date()); user.setName("sssss"); user.setAddress("ddd"); int num=userMapper.updateUser(user); sqlSession.commit(); System.out.println("num="+num); } }
相關文章
相關標籤/搜索