大数据WEB阶段Mybatis(一)
生活随笔
收集整理的這篇文章主要介紹了
大数据WEB阶段Mybatis(一)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Mybatis(一)
零、目錄
- Mybatis介紹
- Mybatis入門案例
- 增刪改查練習(xí)
- 映射文件中取值問題
- Mybatis中單值傳遞和多值傳遞問題
- sql語句的復(fù)用
- 別名標(biāo)簽
- 動態(tài)更新
- 動態(tài)查詢
- 動態(tài)插入
- 批量刪除
一、Mybatis介紹
二、 Mybatis入門案例
添加配置文件
日志文件log4j.properties , 不需要改動直接復(fù)制即可
log4j.rootLogger=DEBUG, Console #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.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUGmybatis核心配置文件
<?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><typeAlias type="com.tj.pojo.User" alias="User"/> </typeAliases> <!-- 配置數(shù)據(jù)源 --><environments default="mysql"><!-- 設(shè)置默認(rèn)使用的數(shù)據(jù)庫配置 , 可以根據(jù)具體情境隨意切換 --><environment id="mysql"><!-- 配置事務(wù)管理 --><transactionManager type="JDBC" /><!-- 表示支持?jǐn)?shù)據(jù)庫連接池 --><dataSource type="POOLED"><!-- 配置數(shù)據(jù)源 --><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment><environment id="oracle"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="oracle.jdbc.driver.OracleDriver" /><property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:XE" /><property name="username" value="ht1602" /><property name="password" value="htdb" /></dataSource></environment></environments><!-- 映射文件 --><mappers><!-- 注意配置的映射文件的路徑 , 而不是全類名 --><mapper resource="com/tj/pojo/UserMapper.xml" /></mappers></configuration>實體類對應(yīng)的映射文件(該文件一般由逆向工程通過數(shù)據(jù)庫配置自動生成實體類和對應(yīng)的映射文件 , 不需要手動寫)
<?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="UserMapper"><sql id="basefind"> select * from user</sql><select id="findAll" resultType="com.tj.pojo.User" >select * from user;</select><insert id="insert" parameterType="com.tj.pojo.User">insert into user(name , age) values( #{name} , #{age});</insert> <delete id="delete">delete from user where id=#{id};</delete><update id="updaet">update user set name=#{name} , age = #{age} where id=#{id}; </update><!-- 根據(jù)名字查詢 用戶 --><select id="findByName" resultType="User"><include refid="basefind"/>where name = #{name};</select> </mapper>測試代碼:
private SqlSession session ; @Before public void init() throws IOException{//獲取一個數(shù)據(jù)流InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");//創(chuàng)建一個工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);//創(chuàng)建一個會話session = factory.openSession(true);//true表示自動提交 , 默認(rèn)為false , 需要手動提交 }@Test public void testFindAll() throws IOException{//執(zhí)行sql語句List<User> users = session.selectList("UserMapper.findAll");System.out.println(users.get(0)); }三、增刪改查練習(xí)
以下案例測試之前先創(chuàng)建會話
private SqlSession session ;@Beforepublic void init() throws IOException{//獲取一個數(shù)據(jù)流InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");//創(chuàng)建一個工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);//創(chuàng)建一個會話session = factory.openSession(true);//true表示自動提交 , 默認(rèn)為false , 需要手動提交}增
映射文件中添加:
<insert id="insert" >insert into user(name , age) values( #{name} , #{age});</insert>測試:
@Testpublic void insertUser() {User user = new User();user.setName("李四");user.setAge(20);//執(zhí)行sql語句session.insert("UserMapper.insert", user);//提交增刪改時都需要commit , 可以在opensession時添加參數(shù)為true設(shè)置文 自動提交session.commit();}刪
映射文件中添加:
<delete id="delete">delete from user where id=#{id};</delete>測試:
@Testpublic void delete() throws IOException{//執(zhí)行sessionsession.delete("UserMapper.delete",3);}改
映射文件中添加:
<update id="update">update user set name=#{name} , age = #{age} where id=#{id}; </update>測試:
@Testpublic void updateUser(){//修改之前先獲取到原數(shù)據(jù)User user = new User();user.setId(1);user.setName("張三");user.setAge(19);//對數(shù)據(jù)進(jìn)行修改user.setName("王五");//執(zhí)行數(shù)據(jù)庫更新操作session.update("UserMapper.update", user);}查
映射文件中添加:
<select id="findAll" resultType="com.tj.pojo.User" >select * from user;</select>測試:
@Testpublic void testFindAll() throws IOException{//執(zhí)行sql語句List<User> users = session.selectList("UserMapper.findAll");System.out.println(users.get(0));}四、映射文件中的取值符號
五、Mybatis映射文件的多值傳遞和單值傳遞
Mybatis中提供的增刪改查方法只支持傳遞一個參數(shù)代表傳入的值
當(dāng)需要傳遞多個 值時, 可以將值放入map中 ;
Mapper文件中:
<select id="finfAllByOrderDesc" resultType="User">select * from user order by ${type} ${paixu};</select>測試:
//多值傳遞 查詢所有用戶并按照年齡 降序排列@Test public void findAllOrderByAgeDesc(){Map<String , String > map = new HashMap<String ,String >();map.put("type", "age");map.put("paixu", "desc");List<User> users = session.selectList("UserMapper.finfAllByOrderDesc" , map);for(User user : users){System.out.println(user);}}當(dāng)傳遞一個值的時候 ,映射文件中取值時可以以任意變量名取值 。
Mapper文件中:
<select id="findByName" resultType="User"><include refid="basefind"/>where name = #{xxxxxx};</select>測試:
//單值傳遞 @Test public void findByName(){User user = session.selectOne("UserMapper.findByName", "王五");System.out.println(user); }六、 sql語句的復(fù)用
聲明:
<sql id="basefind"> select * from user</sql>調(diào)用:
<select id="finfAllByOrderDesc" resultType="User"><include refid="basefind"/>order by ${type} ${paixu};</select>七、別名標(biāo)簽
在核心配置文件中配置別名
<!-- 配置別名 --><typeAliases><typeAlias type="com.tj.pojo.User" alias="User"/></typeAliases>使用
<select id="finfAllByOrderDesc" resultType="User"><include refid="basefind"/>order by ${type} ${paixu};</select>八、 動態(tài)更新
映射文件中sql語句的修改
<!-- 動態(tài) 更新 --><select id="dynamicUpdate">update user<set><if test="name != null">name = #{name} , </if><if test="age != null">age = #{age} , </if></set>where id=#{id}</select>九、 動態(tài)查詢
映射文件中sql語句的修改
<!-- 動態(tài)查詢 --><select id="dyniaicselect"><include refid="basefind"/><where><if test="name != null">name = #{name} </if><if test="age != null"> and age = #{age} </if><if test="id != id"> and id = #{id}</if></where> </select>十、 動態(tài)插入
映射文件中sql語句的修改:
<!-- 動態(tài)插入--><insert id="dyniamicInsert">insert into user <trim prefix="(" suffix=")" suffixOverrides=","><!-- 設(shè)置前綴后綴 , 并且設(shè)置將拼接后最后的逗號去掉 --><if test="name != null">name </if><if test="age != null"> age </if></trim>values<trim prefix="(" suffix=")" suffixOverrides=","><!-- 設(shè)置前綴后綴 , 并且設(shè)置將拼接后最后的逗號去掉 --><if test="name != null">name = #{name} , </if><if test="age != null"> age = #{age} </if></trim></insert>十一、批量刪除
數(shù)組中存放要刪除元素的id
<!-- 動態(tài)刪除 --><delete id="dynamicdelete">delete form user where id in<foreach collection="array" item="id" open="(" close=")"<!-- 參數(shù)類型是數(shù)組 設(shè)置前后綴為() , 并且元素之間用“,”拼接 --> separator=",">#{id}</foreach> </delete>列表中存放要刪除的元素
<!-- 動態(tài)刪除 --><delete id="dynamicdelete">delete form user where id in<foreach collection="list" item="user" open="(" close=")" separator=",">#{user.id}</foreach> </delete>總結(jié)
以上是生活随笔為你收集整理的大数据WEB阶段Mybatis(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大数据WEB阶段Spring框架(四)S
- 下一篇: 大数据WEB阶段Mybatis(二)