Mybatis实例 简单查询 事务处理 关联、集合查询 鉴别器 动态SQL及各种标签实例
2016-11-21 17:31
956 查看
Mybatis 实例
config包 为Mybatis的配置文件,连接数据库配置,加载mappers等
sqlxml包 为各种pojo类对象的xml文件,sql语句在这里编写
pojo包 数据库表对应JavaBean ,实体类
test包 利用Junit测试,MybatisTest.java 为简单的增删改查,2 为多行查询,3为事务,4为关联查询….
log4j.properties 配置控制台输出的一些信息
在MybatisTest4中的
testselectSub方法,进行子查询中,开启懒加载后会出现空指针异常
学习视频网址:http://my.jikexueyuan.com/0HVPjWVkX/record/
Mybatis 工作流程
Mybatis 工作流程 1.读取配置文件 2.生成SqlSessionFactory 3.建立SqlSession 4.调用Mybatis提供的ApI 5.查询MAP配置 6.返回结果
相对于Hibernate,配置更加简单,获取 SqlSession,直接就可以进行各种操作了,主要是配置POJO类(JavaBean)的 xml文件,里面配置各种增删改查方法,resultMap 复杂一些。动态sql配合OGNL(这里没用到),实现各种拼接等。
版本信息
Mybatis 3.4.1 JDK 1.8 Eclipse版本 Neon.1a Release (4.6.1) 数据库 MySQL5.7
Mybatis Jar包下载地址:https://github.com/mybatis/mybatis-3/releases
源代码
源代码会按包分类给出源代码下载:http://download.csdn.net/detail/peng_hong_fu/9689037
数据库db_mybatis
查询,只会用到其中的某些表mysql> show tables; +----------------------+ | Tables_in_db_mybatis | +----------------------+ | tb_author | | tb_reader | | tb_user | | tb_visit | +----------------------+ mysql> desc tb_author; +----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | realName | varchar(20) | YES | | NULL | | | userID | int(11) | YES | | NULL | | | IDCard | varchar(20) | YES | | NULL | | +----------+-------------+------+-----+---------+----------------+ +----+----------+--------+-----------------+ | id | realName | userID | IDCard | +----+----------+--------+-----------------+ | 1 | 金庸 | 5 | 360060040604064 | | 2 | 古龙 | 7 | 360060040604067 | +----+----------+--------+-----------------+ mysql> desc tb_user; +----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | username | varchar(255) | YES | | NULL | | | password | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+----------------+ +----+----------+----------+ | id | username | password | +----+----------+----------+ | 2 | 慕容复 | 666666 | | 4 | 段誉 | 122435 | | 5 | 虚竹 | 43534 | | 7 | 木婉清 | 998989 | +----+----------+----------+ mysql> desc tb_reader; +----------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+---------+------+-----+---------+----------------+ | readerID | int(11) | NO | PRI | NULL | auto_increment | | userID | int(11) | YES | | NULL | | | money | int(11) | YES | | NULL | | +----------+---------+------+-----+---------+----------------+ +----------+--------+-------+ | readerID | userID | money | +----------+--------+-------+ | 1 | 2 | 100 | | 2 | 4 | 300 | | 3 | 5 | 700 | | 4 | 7 | 200 | +----------+--------+-------+ mysql> desc tb_visit; +-----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+----------------+ | visitID | int(11) | NO | PRI | NULL | auto_increment | | userID | int(11) | YES | | NULL | | | visitDate | date | YES | | NULL | | | visitIP | varchar(100) | YES | | NULL | | +-----------+--------------+------+-----+---------+----------------+ +---------+--------+------------+-------------+ | visitID | userID | visitDate | visitIP | +---------+--------+------------+-------------+ | 1 | 2 | 2016-11-12 | 12312.12312 | +---------+--------+------------+-------------+
建表语句如下,其他表类似
mysql> create table tb_reader ( -> readerID int primary key auto_increment, -> userID int, -> money int); Query OK, 0 rows affected (0.51 sec)
表之间存在主键和外键的关联,但建表时没有声明。
tb_user表的主键 id 对应其他表的外键userID列
log4j.properties
配置文件
log4j.properties
log4j.rootLogger=DEBUG,Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.org.apache=INFO log4j.logger.java.sql.ResultSet=INFO log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.Connection=DEBUG
com.jxust.config
包
Configuration.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> <settings> <!-- 懒加载 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings> <!-- 定义别名在 User.xml中引用,可以不用写冗长的包名 --> <typeAliases> <typeAlias alias="User" type="com.jxust.pojo.User"/> <typeAlias alias="Author" type="com.jxust.pojo.Author"/> </typeAliases> <!-- 连接数据库配置 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/db_mybatis?characterEncoding=utf8&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/jxust/config/sqlxml/User.xml"/> <mapper resource="com/jxust/config/sqlxml/Author.xml"/> <mapper resource="com/jxust/config/sqlxml/MyReader.xml"/> <!-- 应用接口来实现删除方法 --> <mapper class="com.jxust.config.sqlxml.InterfaceUserMap"/> </mappers> </configuration>
com.jxust.pojo
包
User.java
package com.jxust.pojo; import java.util.List; /** * 用户信息类对应数据库 tb_user表 * User(用户)包含 Author(作者)和 Reader(读者) * @author Peng * @Date2016年11月20日下午2:55:02 */ public class User { private int id; private String username; private String password; private List<Visit> visitList; // visitList 记入登录事件,每次登录就记入一条数据,所以用List集合 public User() { super(); } public User(String username, String password) { super(); this.username = username; this.password = password; } //setter and getter @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } }
Author.java
package com.jxust.pojo; /** * 作者信息类 对应数据表tb_author * 包含User组件类型 * User a_user对应列userID(外键) * @author Peng * @Date2016年11月20日下午2:55:18 */ public class Author { private Integer id;//自增主键 private User a_user;//外键引用tb_user表 private String realName;//真实姓名 private String IDCard;//身份证 //setter and getter }
Visit.java
package com.jxust.pojo; import java.util.Date; /** * 记录User用户登录的时间,IP信息 * 对应表 tb_visit 表中的 userID键对应v_user * @author Peng * @Date2016年11月21日下午5:06:15 */ public class Visit { private Integer visitID; private User v_user; private Date visitDate; private String visitIP; //setter and getter @Override public String toString() { return "Visit [visitID=" + visitID + ", visitDate=" + visitDate + ", visitIP=" + visitIP + "]"; } }
MyReader.java
package com.jxust.pojo; /** * 记录读者的money,对应表 tb_reader * @author Peng * @Date2016年11月21日上午11:07:33 */ public class MyReader { private Integer readerID; private User r_user;//外键userID,对应tb_user表的主键id private Integer money; //setter and getter @Override public String toString() { return "MyReader [readerID=" + readerID + ", money=" + money + "]"; } }
com.jxust.config.sql.xml
包
User.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="/"> <!-- 配置数据库字段和Message字段 --> <resultMap type="com.jxust.pojo.User" id="UserResult"> <!-- id 主键,result其他列名 --> <!--column属性表示从数据库中查询的属性,property则表示查询出来的属性对应的值赋给实体对象的哪个属性 --> <id column="id" jdbcType="INTEGER" property="id" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="password" jdbcType="VARCHAR" property="password" /> </resultMap> <!-- 和visit表做集合查询 --> <resultMap type="User" id="visitMap"> <id property="id" column="id" /> <result property="username" column="username" /> <result column="password" property="password" /> <collection property="visitList" javaType="ArrayList" column="userID" ofType="com.jxust.pojo.Visit"> <result property="visitID" column="visitID" /> <result property="visitDate" column="visitDate" /> <result property="visitIP" column="visitIP" /> </collection> </resultMap> <!-- 根据id查询 --> <select id="findById" parameterType="int" resultType="com.jxust.pojo.User"> SELECT * FROM tb_user WHERE id=#{id} </select> <!--插入数据 User使用了别名,在配置文件中声明了 --> <insert id="insertUser" parameterType="User" statementType="PREPARED" keyProperty="id" useGeneratedKeys="true"> INSERT INTO tb_user (username,password) VALUES (#{username},#{password}) </insert> <!-- 更新数据 --> <update id="updateuser" parameterType="User"> UPDATE tb_user SET username =#{username,jdbcType=VARCHAR}, password=#{password,jdbcType=VARCHAR} WHERE id=#{id,jdbcType=VARCHAR} </update> <!-- ****************************************************** --> <!-- 删除数据 --> <delete id="deleteuser" parameterType="int"> DELETE FROM tb_user WHERE id=#{id} </delete> <!-- HashMap查询 --> <select id="hashmapselect" resultType="User" parameterType="hashmap"> SELECT * FROM tb_user WHERE username=#{username} AND password=#{password} </select> <!-- 对象查询 返回类型和参数类型都是User --> <select id="objectselect" resultType="User" parameterType="User"> SELECT * FROM tb_user WHERE username=#{username} AND password=#{password} </select> <!-- 返回多行数据 --> <select id="selectUserList" resultType="User"> SELECT * FROM tb_user </select> <!-- resultType 和 resultMap两者只能使用其中一个 --> <select id="selectUsers" resultMap="UserResult"> SELECT id,username,password FROM tb_user </select> <!-- 集合查询 --> <select id="selectVisit" resultMap="visitMap"> SELECT * FROM tb_user INNER JOIN tb_visit ON tb_user.id = tb_visit.userID </select> <!-- 测试 chooose 动态sql 用了别名 --> <select id="selectUserChoose" resultType="User" parameterType="User"> SELECT * FROM tb_user WHERE 1=1 <choose> <when test="username!=null"> AND username like #{username} </when> <when test="id!=0"> AND id=#{id} </when> <otherwise> AND password IS NOT NULL </otherwise> </choose> </select> <!-- 测试 where 动态sql --> <select id="selectUserWhere" resultType="User" parameterType="User"> SELECT * FROM tb_user <where> <if test="username!=null"> AND username like #{username} </if> <if test="id!=0"> AND id =#{id} </if> </where> </select> <!-- 测试 <set> 动态sql --> <!--相对于 UPDATE tb_user SET username= '虚竹' WHERE id =5; 的SET 会判断,的添加 --> <update id="updateUserSet" parameterType="User"> UPDATE tb_user <set> <if test="username!=null"> username = #{username}, </if> <if test="password!=null"> password = #{password}, </if> </set> WHERE id=#{id} </update> <!-- 测试<trim>标签 --> <!-- prefix 前缀增加 suffix 后缀增加 prefixOverrides 自动判断前置 suffixOverrides 自动判断后置 --> <select id="selectUserTrim" parameterType="User" resultType="User"> SELECT * FROM tb_user <trim prefix="WHERE" prefixOverrides="AND|OR"> <if test="username!=null and username!='' "> AND username like #{username} </if> <if test="password!=null and password!='' "> AND password =#{password} </if> </trim> </select> <!-- 测试<trim>标签 2--> <!-- 智能添加后缀,如果你username和password都没有赋值,则,语句为 UPDATE tb_user当然,这个语句会报错 --> <update id="updateUserTrim" parameterType="USer"> UPDATE tb_user <trim prefix="SET" suffixOverrides="," suffix="WHERE id=#{id}"> <if test="username != null and username != '' "> username = #{username}, </if> <if test="password != null and password != '' "> password = #{password}, </if> </trim> </update> <!-- 测试foreach标记 --> <!-- 这里可以不指定 parameterType --> <select id="selectUserforeach" parameterType="java.util.List" resultType="User"> SELECT * FROM tb_user <where> id IN <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </where> </select> </mapper>
Author.java
<?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="/"> <!--**联合查询 resultMap** --> <!-- 配置数据库字段和Message字段 没有使用别名,怕混淆--> <resultMap type="com.jxust.pojo.Author" id="AuthorresultMapByJoin"> <!-- column属性表示从数据库中查询的属性,property则表示查询出来的属性对应的值赋给实体对象的哪个属性 --> <id column="tb_author.id" jdbcType="INTEGER" property="id"/> <result column="realName" jdbcType="VARCHAR" property="realName"/> <result column="IDCard" jdbcType="VARCHAR" property="IDCard"/> <!-- property为Author类中private User a_user;column为数据库表中的列userID --> <!-- 两个表的id相同,为了区分,使用表名加id,tb_user.id 和 tb_author.id --> <association property="a_user" column="userID" javaType="com.jxust.pojo.User"> <id column="tb_user.id" jdbcType="INTEGER" property="id"/> <result column="username" jdbcType="VARCHAR" property="username"/> <result column="password" jdbcType="VARCHAR" property="password"/> </association> </resultMap> <!-- **构造查询方式resultMap** --> <resultMap type="com.jxust.pojo.Author" id="AuthorresultMapByCon"> <id column="tb_author.id" jdbcType="INTEGER" property="id"/> <result column="realName" jdbcType="VARCHAR" property="realName"/> <result column="IDCard" jdbcType="VARCHAR" property="IDCard"/> <association property="a_user" column="userID" javaType="com.jxust.pojo.User"> <constructor> <arg column="username" javaType="String" /> <arg column="password" javaType="String"/> </constructor> </association> </resultMap> <!-- **子查询方式resultMap** --> <resultMap type="com.jxust.pojo.Author" id="AuthorresultMapBySub"> <id column="tb_author.id" jdbcType="INTEGER" property="id"/> <result column="realName" jdbcType="VARCHAR" property="realName"/> <result column="IDCard" jdbcType="VARCHAR" property="IDCard"/> <association property="a_user" column="userID" javaType="com.jxust.pojo.User" select="findById"> <!-- 会把userId 传入到findById(在User.xml文件中)查询中 --> </association> </resultMap> <!-- *********************************************************** --> <!-- 插入一条数据 --> <insert id="insertAuthor" parameterType="Author" > INSERT INTO tb_author (userID,realName,IDCard) VALUES(#{a_user.id},#{realName},#{IDCard}) </insert> <!--联合查询 --> <select id="selectAuthorJoin" resultMap="AuthorresultMapByJoin"> SELECT * FROM tb_author INNER JOIN tb_user ON tb_user.id = tb_author.userID </select> <!-- 联合查询 注意引用的resultMap不同 --> <select id="selectAuthorCon" resultMap="AuthorresultMapByCon"> SELECT * FROM tb_author INNER JOIN tb_user ON tb_user.id = tb_author.userID </select> <!-- 子查询 --> <select id="selectAuthorSub" resultMap="AuthorresultMapBySub"> SELECT * FROM tb_author </select> </mapper>
InterfaceUserMap.java
package com.jxust.config.sqlxml; import org.apache.ibatis.annotations.Delete; public interface InterfaceUserMap { @Delete("DELETE FROM tb_user WHERE id=#{id}") public void deleteoneuser(Integer id); }
MyReader.java
<?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="/"> <!-- 测试 if 动态sql --> <select id="selectReaderMoney" resultType="com.jxust.pojo.MyReader" parameterType="com.jxust.pojo.MyReader"> SELECT * FROM tb_reader WHERE 1=1 <if test="money!=null"> and money>#{money} </if> </select> </mapper>
com.jxust.test
MybatisTest.java
package com.jxust.test; import org.junit.Test; import com.jxust.config.sqlxml.InterfaceUserMap; import com.jxust.pojo.User; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * 简单的增删改查 * @author Peng * @Date2016年11月20日上午11:27:07 */ public class MybatisTest { /** * 测试查询 * @throws IOException */ @Test public void testfindById() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); //通过配置信息构建一个SqlSessionFactory SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); //通过SqlSessionFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = sqlSession.selectOne("findById", 2); System.out.println(user.toString()); } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试插入一条数据 * @throws IOException */ @Test public void testinsert() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setUsername("段誉"); user.setPassword("122435"); sqlSession.insert("insertUser",user); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 更新数据 * @throws IOException */ @Test public void testupdate() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setUsername("慕容复"); user.setPassword("666666"); user.setId(2); sqlSession.update("updateuser", user); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 删除数据,利用注解的方式(使用接口) 不推荐 * @throws IOException */ @Test public void testdelete() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { InterfaceUserMap ium = sqlSession.getMapper(InterfaceUserMap.class); ium.deleteoneuser(1); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 删除数据,采用xml文件 * @throws IOException */ @Test public void testdelete2() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { sqlSession.delete("deleteuser", 3); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } }
MybatisTest2.java
package com.jxust.test; import java.io.IOException; import java.io.Reader; import java.util.HashMap; 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.Test; import com.jxust.pojo.User; /** * 简单查询、多行查询 * @author Peng * @Date2016年11月20日上午11:28:31 */ public class MybatisTest2 { /** * 测试hashmap查询 * @throws IOException */ @Test public void testlogin() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); //通过配置信息构建一个SqlSessionFactory SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); //通过SqlSessionFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); try { HashMap<String,String> map = new HashMap<>(); map.put("username", "慕容复"); map.put("password", "666666"); User user =sqlSession.selectOne("hashmapselect",map); if(user!=null){ System.out.println("登录成功!"); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试对象查询 * @throws IOException */ @Test public void testlogin2() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); //通过配置信息构建一个SqlSessionFactory SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); //通过SqlSessionFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setUsername("慕容复"); user.setPassword("666666"); User rs_user =sqlSession.selectOne("objectselect",user); if(rs_user!=null){ System.out.println("登录成功!"); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试多行查询 * @throws IOException */ @Test public void testselectlist() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); //通过配置信息构建一个SqlSessionFactory SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); //通过SqlSessionFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<User> list = sqlSession.selectList("selectUserList"); for(User s :list){ System.out.println(s.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试resultMap查询 * @throws IOException */ @Test public void testselectresultMap() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); //通过配置信息构建一个SqlSessionFactory SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); //通过SqlSessionFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<User> list = sqlSession.selectList("selectUsers"); for(User s :list){ System.out.println(s.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } }
MybatisTest3.java
package com.jxust.test; import java.io.IOException; import java.io.Reader; 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.Test; import com.jxust.pojo.Author; import com.jxust.pojo.User; /** * 测试事务 * @author Peng * @Date2016年11月20日下午2:38:02 */ public class MybatisTest3 { /** * 测试添加数据,人为制造错误,查看事务回滚效果 * @throws IOException */ @Test public void testinsertTranscation() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(false); //默认为false try { User one = new User(); one.setUsername("author02"); one.setPassword("43535"); //存入数据库之后,id值自动生成 sqlSession.insert("insertUser",one); System.out.println("新加入的user id为"+one.getId()); Author au = new Author(); au.setUser(one); au.setRealName("古龙"); au.setIDCard("360060040604067"); sqlSession.insert("insertAuthor",au); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 sqlSession.rollback(); }finally { sqlSession.close(); } } }
MybatisTest4.java
package com.jxust.test; import java.io.IOException; import java.io.Reader; 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.Test; import com.jxust.pojo.Author; /** * 测试关联查询 * @author Peng * @Date2016年11月20日下午3:37:10 */ public class MybatisTest4 { /** * 测试关联查询-联合查询 * @throws IOException */ @Test public void testselectJoin() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<Author> list = sqlSession.selectList("selectAuthorJoin"); for(Author a:list){ System.out.println("作者姓名:"+a.getRealName()+","+ "对应用户名:"+a.getUser().getUsername()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试关联查询-构造查询 * @throws IOException */ @Test public void testselectConstruct() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<Author> list = sqlSession.selectList("selectAuthorCon"); for(Author a:list){ System.out.println("作者姓名:"+a.getRealName()+","+ "对应用户名:"+a.getUser().getUsername()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试关联查询-子查询 * @throws IOException */ @Test public void testselectSub() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<Author> list = sqlSession.selectList("selectAuthorSub"); for(Author a:list){ //System.out.println("作者姓名:"+a.getRealName()+","+ //"对应用户名:"+a.getUser().getUsername()); System.out.println("作者姓名:"+a.getRealName()); System.out.println("懒加载应用....."); /* -----------------这里有错误--------------*/ //设置为懒加载后会出现空指针异常,没有执行findById查询 if(a.getUser()==null){ System.out.println("a.getUser()为空"); } System.out.println("对应用户名:"+a.getUser().getUsername()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } }
MybatisTest5.java
package com.jxust.test; import java.io.IOException; import java.io.Reader; 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.Test; import com.jxust.pojo.User; import com.jxust.pojo.Visit; /** * 测试集合查询 * @author Peng * @Date2016年11月20日下午8:05:19 */ public class MybatisTest5 { /** * 测试集合查询 * 集合查询特定用于当你查询的对象中含有另一个对象的集合引用时 * @throws IOException */ @Test public void testselectColl() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<User> list = sqlSession.selectList("selectVisit"); for(User u:list){ System.out.println(u.toString()); for(Visit v:u.getVisitList()){ System.out.println(v.toString()); } } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } }
MybatisTest6.java
package com.jxust.test; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; 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.Test; import com.jxust.pojo.MyReader; import com.jxust.pojo.User; /** * 测试动态SQL * @author Peng * @Date2016年11月20日下午8:05:19 */ public class MybatisTest6 { /** * 测试 <if>标记 * 在Myreader.xml文件中配置的 * @throws IOException */ @Test public void testselectIF() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { MyReader myreader = new MyReader(); //myreader.setMoney(200); List<MyReader> list = sqlSession.selectList("selectReaderMoney",myreader); for(MyReader m:list){ System.out.println(m.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试 <choose>标记 * 非常像switch * 在User.xml文件中配置的 * @throws IOException */ @Test public void testselectChoose() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); //user.setUsername("%段%"); //user.setId(4); //可以设置 List<User> list = sqlSession.selectList("selectUserChoose",user); for(User s:list){ System.out.println(s.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试 <where>标记 * 在User.xml文件中配置的 * 就是<where>替换掉sql语句中的WHERE,就不用写1=1了, * <where>智能的判断该不该加WHERE * 避免 SELECT * FROM tb_user WHERE ,WHERE后面没内容,出现语法错误 * @throws IOException */ @Test public void testselectWhere() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); //user.setUsername("%段%"); user.setId(4); List<User> list = sqlSession.selectList("selectUserWhere",user); for(User s:list){ System.out.println(s.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试 <set>标记 * 在User.xml文件中配置的 * 智能判断set 内容后面的"," * UPDATE tb_user SET username= '虚竹',..., WHERE ... * @throws IOException */ @Test public void testupdateSet() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setUsername("木婉清"); //user.setPassword("998989"); user.setId(7); sqlSession.update("updateUserSet",user); sqlSession.commit();//注意要提交 } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试 <trim>标记 * 在User.xml文件中配置的 * * @throws IOException */ @Test public void testselectTrim() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setUsername("%段%"); //user.setPassword("122435"); List<User> list = sqlSession.selectList("selectUserTrim",user); for(User s:list){ System.out.println(s.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试 <trim标记 * 在User.xml文件中配置的 * * @throws IOException */ @Test public void testupdateTrim() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); //user.setUsername("木婉清"); //user.setPassword("998989"); user.setId(7); sqlSession.update("updateUserTrim",user); sqlSession.commit();//注意要提交 } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } /** * 测试<foreach>标记 * @throws IOException */ @Test public void testselectForeach() throws IOException{ Reader reader =Resources.getResourceAsReader("com/jxust/config/Configuration.xml"); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(5); List<User> userlist = sqlSession.selectList("selectUserforeach",list); for(User s:userlist){ System.out.println(s.toString()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } } }
Mybatis笔记
记录一些控制台配置信息,和异常等MyBatis笔记.txt
----------------------------------------------------
mybatisConfig.xml中引用map文件
1
<mapers>
<mapper resource="jxust/map/User.xml"/>
</mappers>
2绝对路径引用
<mapper url ="file:///var/sqlmaps/User.xml/>
3包路径引用
<package name="com.xx.mapperinterface"/>
----------------------------------------------------
mysql> desc tb_user;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(255) | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
----------------------------------------------------
查询数据
2016-11-19 21:33:24,265 [main] DEBUG [User.findById] - ==> Preparing: select * from tb_user where id=?
2016-11-19 21:33:24,301 [main] DEBUG [User.findById] - ==> Parameters: 1(Integer)
2016-11-19 21:33:24,336 [main] DEBUG [User.findById] - <== Total: 1
User [id=1, username=李琦, password=123345]
----------------------------------------------------
插入数据
2016-11-19 22:02:54,866 [main] DEBUG [/.insertUser] - ==> Preparing: insert into tb_user (username,password) values (?,?)
2016-11-19 22:02:54,924 [main] DEBUG [/.insertUser] - ==> Parameters: 慕容复(String), 123445(String)
2016-11-19 22:02:54,961 [main] DEBUG [/.insertUser] - <== Updates: 1
----------------------------------------------------
插入数据,没有指定的属性为null
2016-11-20 10:21:50,799 [main] DEBUG [/.updateuser] - ==> Preparing: UPDATE tb_user SET username =?, password=? WHERE id=?
2016-11-20 10:21:50,836 [main] DEBUG [/.updateuser] - ==> Parameters: null, 666666(String), 2(Integer)
2016-11-20 10:21:50,841 [main] DEBUG [/.updateuser] - <== Updates: 1
username没有赋值
mysql> select * from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | 李琦 | 123345 |
| 2 | NULL | 666666 |
+----+----------+----------+
2 rows in set (0.00 sec)
2016-11-20 10:24:02,379 [main] DEBUG [/.updateuser] - ==> Preparing: UPDATE tb_user SET username =?, password=? WHERE id=?
2016-11-20 10:24:02,413 [main] DEBUG [/.updateuser] - ==> Parameters: 慕容复(String), 666666(String), 2(Integer)
2016-11-20 10:24:02,417 [main] DEBUG [/.updateuser] - <== Updates: 1
mysql> select * from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | 李琦 | 123345 |
| 2 | 慕容复 | 666666 |
+----+----------+----------+
2 rows in set (0.00 sec)
----------------------------------------------------
删除一条数据,通过注解的方式,接口的方式
2016-11-20 10:32:02,230 [main] DEBUG [com.jxust.config.sqlxml.InterfaceUserMap.deleteuser] - ==> Preparing: DELETE FROM tb_user WHERE id=?
2016-11-20 10:32:02,263 [main] DEBUG [com.jxust.config.sqlxml.InterfaceUserMap.deleteuser] - ==> Parameters: 1(Integer)
2016-11-20 10:32:02,267 [main] DEBUG [com.jxust.config.sqlxml.InterfaceUserMap.deleteuser] - <== Updates: 1
mysql> select * from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 2 | 慕容复 | 666666 |
+----+----------+----------+
1 row in set (0.00 sec)
----------------------------------------------------
利用hashmap封装数据查询
2016-11-20 11:34:17,236 [main] DEBUG [/.hashmapselect] - ==> Preparing: SELECT * FROM tb_user WHERE username=? AND password=?
2016-11-20 11:34:17,273 [main] DEBUG [/.hashmapselect] - ==> Parameters: 慕容复(String), 666666(String)
2016-11-20 11:34:17,300 [main] DEBUG [/.hashmapselect] - <== Total: 1
登录成功!
利用 对象查询
2016-11-20 12:21:25,075 [main] DEBUG [/.objectselect] - ==> Preparing: SELECT * FROM tb_user WHERE username=? AND password=?
2016-11-20 12:21:25,103 [main] DEBUG [/.objectselect] - ==> Parameters: 慕容复(String), 666666(String)
2016-11-20 12:21:25,115 [main] DEBUG [/.objectselect] - <== Total: 1
登录成功!
----------------------------------------------------
多行查询
2016-11-20 11:57:39,277 [main] DEBUG [/.selectUserList] - ==> Preparing: SELECT * FROM tb_user
2016-11-20 11:57:39,303 [main] DEBUG [/.selectUserList] - ==> Parameters:
2016-11-20 11:57:39,317 [main] DEBUG [/.selectUserList] - <== Total: 2
User [id=2, username=慕容复, password=666666]
User [id=4, username=段誉, password=122435]
----------------------------------------------------
resultMap 方式查询所有
2016-11-20 12:20:15,150 [main] DEBUG [/.selectUsers] - ==> Preparing: SELECT id,username,password FROM tb_user
2016-11-20 12:20:15,180 [main] DEBUG [/.selectUsers] - ==> Parameters:
2016-11-20 12:20:15,193 [main] DEBUG [/.selectUsers] - <== Total: 2
User [id=2, username=慕容复, password=666666]
User [id=4, username=段誉, password=122435]
----------------------------------------------------
创建表 Author
mysql> create table Author(
-> id int primary key auto_increment,
-> realName varchar(20),
-> userID int,
-> IDCard varchar(20));
Query OK, 0 rows affected (0.26 sec)
mysql> desc Author;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| realName | varchar(20) | YES | | NULL | |
| userID | int(11) | YES | | NULL | |
| IDCard | varchar(20) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
----------------------------------------------------
执行过程中,其中一个操作出错,则执行回滚
2016-11-20 14:50:04,521 [main] DEBUG [/.insertUser] - ==> Preparing: INSERT INTO tb_user (username,password) VALUES (?,?)
2016-11-20 14:50:04,548 [main] DEBUG [/.insertUser] - ==> Parameters: author01(String), 43534(String)
2016-11-20 14:50:04,601 [main] DEBUG [/.insertUser] - <== Updates: 1
新加入的user id为6
org.apache.ibatis.exceptions.PersistenceException:
执行成功,打印出两条sql语句
2016-11-20 14:59:26,725 [main] DEBUG [/.insertUser] - ==> Preparing: INSERT INTO tb_user (username,password) VALUES (?,?)
2016-11-20 14:59:26,749 [main] DEBUG [/.insertUser] - ==> Parameters: author02(String), 43535(String)
2016-11-20 14:59:26,802 [main] DEBUG [/.insertUser] - <== Updates: 1
新加入的user id为7
2016-11-20 14:59:26,803 [main] DEBUG [/.insertAuthor] - ==> Preparing: INSERT INTO tb_author (userID,realName,IDCard) VALUES(?,?,?)
2016-11-20 14:59:26,803 [main] DEBUG [/.insertAuthor] - ==> Parameters: 7(Integer), 古龙(String), 360060040604067(String)
2016-11-20 14:59:26,806 [main] DEBUG [/.insertAuthor] - <== Updates: 1
----------------------------------------------------
联合查询
2016-11-20 15:46:28,123 [main] DEBUG [/.selectAuthorJoin] - ==> Preparing: SELECT * FROM tb_author INNER JOIN tb_user ON tb_user.id = tb_author.userID
2016-11-20 15:46:28,152 [main] DEBUG [/.selectAuthorJoin] - ==> Parameters:
2016-11-20 15:46:28,168 [main] DEBUG [/.selectAuthorJoin] - <== Total: 2
作者姓名:金庸,对应用户名:author01
作者姓名:古龙,对应用户名:author02
----------------------------------------------------
构造查询
2016-11-20 17:02:05,165 [main] DEBUG [/.selectAuthorCon] - ==> Preparing: SELECT * FROM tb_author INNER JOIN tb_user ON tb_user.id = tb_author.userID
2016-11-20 17:02:05,194 [main] DEBUG [/.selectAuthorCon] - ==> Parameters:
2016-11-20 17:02:05,211 [main] DEBUG [/.selectAuthorCon] - <== Total: 2
作者姓名:金庸,对应用户名:author01
作者姓名:古龙,对应用户名:author02
----------------------------------------------------
子查询
2016-11-20 16:59:59,687 [main] DEBUG [/.selectAuthorSub] - ==> Preparing: SELECT * FROM tb_author
2016-11-20 16:59:59,714 [main] DEBUG [/.selectAuthorSub] - ==> Parameters:
2016-11-20 16:59:59,732 [main] DEBUG [/.findById] - ====> Preparing: SELECT * FROM tb_user WHERE id=?
2016-11-20 16:59:59,733 [main] DEBUG [/.findById] - ====> Parameters: 5(Integer)
2016-11-20 16:59:59,735 [main] DEBUG [/.findById] - <==== Total: 1
2016-11-20 16:59:59,736 [main] DEBUG [/.findById] - ====> Preparing: SELECT * FROM tb_user WHERE id=?
2016-11-20 16:59:59,736 [main] DEBUG [/.findById] - ====> Parameters: 7(Integer)
2016-11-20 16:59:59,738 [main] DEBUG [/.findById] - <==== Total: 1
2016-11-20 16:59:59,738 [main] DEBUG [/.selectAuthorSub] - <== Total: 2
作者姓名:金庸,对应用户名:author01
作者姓名:古龙,对应用户名:author02
----------------------------------------------------
mysql> use db_mybatis;
Database changed
mysql> create table visit(
-> visitID int primary key auto_increment,
-> userID int ,
-> visitDate Date,
-> visitIP varchar(100));
Query OK, 0 rows affected (0.24 sec)
mysql> desc visit;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| visitID | int(11) | NO | PRI | NULL | auto_increment |
| userID | int(11) | YES | | NULL | |
| visitDate | date | YES | | NULL | |
| visitIP | varchar(100) | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> rename table visit to tb_visit;
Query OK, 0 rows affected (0.23 sec)
mysql> show tables;
+----------------------+
| Tables_in_db_mybatis |
+----------------------+
| tb_author |
| tb_user |
| tb_visit |
+----------------------+
3 rows in set (0.00 sec)
----------------------------------------------------
集合查询,password 为null 是因为我在设置resultMap 时没有加<result column="password" property="password"/>
所以这就是resultMap的特点,结果集映射,自己定义类型,有collection查询 和association查询两种方式,关联查询又分联合,构造,子查询
2016-11-20 20:08:47,473 [main] DEBUG [/.selectVisit] - ==> Preparing: SELECT * FROM tb_user INNER JOIN tb_visit ON tb_user.id = tb_visit.userID
2016-11-20 20:08:47,500 [main] DEBUG [/.selectVisit] - ==> Parameters:
2016-11-20 20:08:47,518 [main] DEBUG [/.selectVisit] - <== Total: 1
User [id=2, username=慕容复, password=null]
Visit [visitID=1, visitDate=Sat Nov 12 00:00:00 CST 2016, visitIP=12312.12312]
----------------------------------------------------
mysql> show tables;
+----------------------+
| Tables_in_db_mybatis |
+----------------------+
| tb_author |
| tb_user |
| tb_visit |
+----------------------+
3 rows in set (0.00 sec)
----------------------------------------------------
新建一张表 tb_reader
mysql> create table tb_reader ( -> readerID int primary key auto_increment, -> userID int, -> money int); Query OK, 0 rows affected (0.51 sec)
mysql>
mysql> show tables;
+----------------------+
| Tables_in_db_mybatis |
+----------------------+
| tb_author |
| tb_reader |
| tb_user |
| tb_visit |
+----------------------+
4 rows in set (0.00 sec)
mysql> desc tb_reader;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| readerID | int(11) | NO | PRI | NULL | auto_increment |
| userID | int(11) | YES | | NULL | |
| money | int(11) | YES | | NULL | |
+----------+---------+------+-----+---------+----------------+
3 rows in set (0.08 sec)
----------------------------------------------------
测试if拼接查询
设置为money大于200 myreader.setMoney(200);
2016-11-21 11:24:39,709 [main] DEBUG [/.selectReaderMoney] - ==> Preparing: SELECT * FROM tb_reader WHERE 1=1 and money>?
2016-11-21 11:24:39,733 [main] DEBUG [/.selectReaderMoney] - ==> Parameters: 200(Integer)
2016-11-21 11:24:39,782 [main] DEBUG [/.selectReaderMoney] - <== Total: 2
MyReader [readerID=2, money=300]
MyReader [readerID=3, money=700]
将设置money注释 //myreader.setMoney(200);则查询所有
2016-11-21 11:26:58,290 [main] DEBUG [/.selectReaderMoney] - ==> Preparing: SELECT * FROM tb_reader WHERE 1=1
2016-11-21 11:26:58,314 [main] DEBUG [/.selectReaderMoney] - ==> Parameters:
2016-11-21 11:26:58,328 [main] DEBUG [/.selectReaderMoney] - <== Total: 4
MyReader [readerID=1, money=100]
MyReader [readerID=2, money=300]
MyReader [readerID=3, money=700]
MyReader [readerID=4, money=200]
----------------------------------------------------
测试choose标签
user.setUsername("%段%");
user.setId(4);
2016-11-21 13:53:21,779 [main] DEBUG [/.selectUserChoose] - ==> Preparing: SELECT * FROM tb_user WHERE 1=1 AND username like ?
2016-11-21 13:53:21,820 [main] DEBUG [/.selectUserChoose] - ==> Parameters: %段%(String)
2016-11-21 13:53:21,848 [main] DEBUG [/.selectUserChoose] - <== Total: 1
User [id=4, username=段誉, password=122435]
//user.setUsername("%段%");
user.setId(4);
2016-11-21 13:55:20,505 [main] DEBUG [/.selectUserChoose] - ==> Preparing: SELECT * FROM tb_user WHERE 1=1 AND id=?
2016-11-21 13:55:20,531 [main] DEBUG [/.selectUserChoose] - ==> Parameters: 4(Integer)
2016-11-21 13:55:20,543 [main] DEBUG [/.selectUserChoose] - <== Total: 1
User [id=4, username=段誉, password=122435]
//user.setUsername("%段%");
///user.setId(4);
都注释后,因为User类中 id的类型为int型,没有设置的时候,默认为0,出现下面的语句,应该把id判断为0,而不是空
2016-11-21 13:55:20,505 [main] DEBUG [/.selectUserChoose] - ==> Preparing: SELECT * FROM tb_user WHERE 1=1 AND id=?
2016-11-21 13:55:20,531 [main] DEBUG [/.selectUserChoose] - ==> Parameters: 0(Integer)
2016-11-21 13:55:20,543 [main] DEBUG [/.selectUserChoose] - <== Total: 0
把SELECT中的语句id判断是否为0,出现判断password的值
<when test="id!=0">
AND id=#{id}
</when>
2016-11-21 13:59:33,054 [main] DEBUG [/.selectUserChoose] - ==> Preparing: SELECT * FROM tb_user WHERE 1=1 AND password IS NOT NULL
2016-11-21 13:59:33,098 [main] DEBUG [/.selectUserChoose] - ==> Parameters:
2016-11-21 13:59:33,110 [main] DEBUG [/.selectUserChoose] - <== Total: 4
User [id=2, username=慕容复, password=666666]
User [id=4, username=段誉, password=122435]
User [id=5, username=author01, password=43534]
User [id=7, username=author02, password=43535]
--------------------------------------------------
测试<where>标签
username 和 id 都没有添加,查询的是下面的语句
2016-11-21 14:23:18,714 [main] DEBUG [/.selectUserWhere] - ==> Preparing: SELECT * FROM tb_user
2016-11-21 14:23:18,740 [main] DEBUG [/.selectUserWhere] - ==> Parameters:
2016-11-21 14:23:18,754 [main] DEBUG [/.selectUserWhere] - <== Total: 4
User [id=2, username=慕容复, password=666666]
User [id=4, username=段誉, password=122435]
User [id=5, username=author01, password=43534]
User [id=7, username=author02, password=43535]
--------------------------------------------------
set 标签测试,逗号被智能去除了
2016-11-21 14:43:44,303 [main] DEBUG [/.updateUserSet] - ==> Preparing: UPDATE tb_user SET username = ? WHERE id=?
2016-11-21 14:43:44,328 [main] DEBUG [/.updateUserSet] - ==> Parameters: 木婉清(String), 7(Integer)
2016-11-21 14:43:44,380 [main] DEBUG [/.updateUserSet] - <== Updates: 1
mysql> select* from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 2 | 慕容复 | 666666 |
| 4 | 段誉 | 122435 |
| 5 | 虚竹 | 43534 |
| 7 | author02 | 43535 |
+----+----------+----------+
4 rows in set (0.00 sec)
mysql> select* from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 2 | 慕容复 | 666666 |
| 4 | 段誉 | 122435 |
| 5 | 虚竹 | 43534 |
| 7 | 木婉清 | 43535 |
+----+----------+----------+
4 rows in set (0.00 sec)
--------------------------------------------------
<!-- 测试<trim>标签 -->
user.setUsername("%段%");
//user.setPassword("122435");
List<User> list = sqlSession.selectList("selectUserTrim",user);
2016-11-21 15:14:41,513 [main] DEBUG [/.selectUserTrim] - ==> Preparing: SELECT * FROM tb_user WHERE username like ?
2016-11-21 15:14:41,537 [main] DEBUG [/.selectUserTrim] - ==> Parameters: %段%(String)
2016-11-21 15:14:41,550 [main] DEBUG [/.selectUserTrim] - <== Total: 1
User [id=4, username=段誉, password=122435]
4 rows in set (0.00 sec)
<!-- 测试<trim>标签2 -->
//user.setUsername("木婉清");
user.setPassword("998989");
user.setId(7);
sqlSession.update("updateUserTrim",user);
sqlSession.commit();//注意要提交
2016-11-21 15:23:00,263 [main] DEBUG [/.updateUserTrim] - ==> Preparing: UPDATE tb_user SET password = ? WHERE id=?
2016-11-21 15:23:00,288 [main] DEBUG [/.updateUserTrim] - ==> Parameters: 998989(String), 7(Integer)
2016-11-21 15:23:00,290 [main] DEBUG [/.updateUserTrim] - <== Updates: 1
--------------------------------------------------
测试foreach 标签
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 2 | 慕容复 | 666666 |
| 4 | 段誉 | 122435 |
| 5 | 虚竹 | 43534 |
| 7 | 木婉清 | 998989 |
+----+----------+----------+
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(5);
List<User> userlist = sqlSession.selectList("selectUserforeach",list);
2016-11-21 16:01:29,184 [main] DEBUG [/.selectUserforeach] - ==> Preparing: SELECT * FROM tb_user WHERE id IN ( ? , ? , ? )
2016-11-21 16:01:29,210 [main] DEBUG [/.selectUserforeach] - ==> Parameters: 1(Integer), 2(Integer), 5(Integer)
2016-11-21 16:01:29,223 [main] DEBUG [/.selectUserforeach] - <== Total: 2
User [id=2, username=慕容复, password=666666]
User [id=5, username=虚竹, password=43534]
查询<select>
参数
id 在这个模式下唯一的标识符,可被其它语句引用 parameterType 传给此语句的参数的完整类名或别名 resultType 语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用) resultMap 引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用) flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 fetchSize 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 statementType statement,preparedstatement,callablestatement。预准备语句、可调用语句。可选值为(STATEMENT/PREPARED/CALLABLE),默认为PREPARED resultSetType forward_only,scroll_sensitive,scroll_insensitive 只转发,滚动敏感,不区分大小写的滚动,可选值(FORWARD_ONLY/SCROLL_SENSITIVE/SCROLL_INSENSITIVE)
resultMap 用来解决复杂的映射关系,比如一个对象含有另一个对象中的引用
事务处理
Mybatis事务由两种方式控制JDBC
MANAGED
... <environment id="development"> <transactionManager type="JDBC"> </transactionManager> </environment> ...
SqlSession sqlSession = sqlSessionFactory.openSession(false); //默认为false try { User one = new User(); one.setUsername("author01"); one.setPassword("43534"); //存入数据库之后,id值自动生成 sqlSession.insert("insertUser",one); System.out.println("新加入的user id为"+one.getId()); Author au = new Author(); au.setUser(one); au.setRealName("金庸"); au.setIDCard("360060040604064"); sqlSession.insert("insertAuthor333",au); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 sqlSession.rollback(); }finally { sqlSession.close(); }
有两个执行持久化操作的行为 ,任何一个错误都会导致,sqlSession提交失败,事务回滚
保证数据库数据的完整性和一致性
Mybatis 异常和错误
PersistenceException
一:
org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 31; columnNumber: 105; 对实体 "useSSL" 的引用必须以 ';' 分隔符结尾。
<property name="url" value="jdbc:mysql://127.0.0.1:3306/db_mybatis?characterEncoding=utf8&useSSL=true"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/db_mybatis?characterEncoding=utf8&useSSL=true"/>
二:
org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in com/jxust/config/sqlxml/User.xml ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for /.hashmapselect
比如像下面一样的id重名
<!-- HashMap查询 --> <select id="hashmapselect" resultType="User" parameterType="hashmap"> SELECT * FROM tb_user WHERE username=#{username} AND password=#{password} </select> <!-- 对象查询 --> <select id="hashmapselect" resultType="User" parameterType="User"> SELECT * FROM tb_user WHERE username=#{username} AND password=#{password} </select>
IllegalArgumentException
Caused by: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for
没指定调用xml中的方法,写了 “”
List<User> list = sqlSession.selectList("");
鉴别器
discriminator 标记javaType 属性
column 属性
case子标记
<discriminator javaType="" column=""> <case value=""> .... </case> </discriminator>
一个表的字段如下:
当要添加一条数据时,根据性别来决定添加 Husband 字段或者是 wife 字段
鉴别器,就是会根据某个字段的值,来选择为部分字段来赋值
性别为男时,添加的是 wife 字段,否则为 Husband 字段
<discriminator javaType="" column=""> <case value="1"> <result property="husband" column="husband" </case> case value="2"> <result property="wife" column="wife" </case> </discriminator>
复杂的鉴别器
不同会员等级对应不同等级对象
Class GenneralClass extends UserClass //普通会员,等级为1 Class SeniorClass extends UserClass //高级会员,等级为2 Class VIPClass extends UserClass //VIP会员,等级为3
鉴别等级,来决定实例化不同的类,等级为1,示例化GenneralClass 类。
相关文章推荐
- spring多数据源的处理 mybatis实现跨库查询 实现Myibatis动态sql跨数据库的处理 Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样
- MyBatis代码实例系列-06:Mybatis动态SQL标签(一)---if、where、set、trim、choose
- mybatis动态查询之foreach,sql标签查询
- MyBatis的一系列问题的处理(遍历Map集合和智能标签和属性和字段不一样的解决办法 和sql片段)(三)
- mybatis动态查询 sql标签和include标签的使用
- MyBatis的动态SQL查询常用几种标签
- MyBatis动态SQL标签用法实例详解
- MyBatis代码实例系列-07:Mybatis动态SQL标签(二)---bind、foreach和多数据库厂商支持_databaseId
- MyBatis动态查询 模糊查询实例sql
- MyBatis的动态SQL详解-各种标签使用
- 使用动态SQL语句是最简单的处理方法。
- 利用MyBatis的动态SQL特性抽象统一SQL查询接口
- MyBatis动态SQL中trim标签的使用
- Mybatis上路_03-简单关联数据查询
- 动态SQL中的查询条件参数化处理
- T-SQL查询:行列转换简单实例
- PostgreSQL服务过程中的那些事二:Pg服务进程处理简单查询二:SQL解析为parsetree
- SQL 查询数据(四.集合查询) 实例_(学生,课程表,选修表)
- 简单修改Hibernate源码,增加使用原生SQL查询时动态addEntity和addScalar功能
- 动态SQL— —模糊查询语句(存储过程)中关于百分号%的处理