您好,登錄后才能下訂單哦!
前言
開博客這是第一次寫系列文章,從內(nèi)心上講是有點(diǎn)擔(dān)心自己寫不好,寫不全,畢竟是作為java/mybatis學(xué)習(xí)的過程想把學(xué)習(xí)的路線和遇到的問題都總結(jié)下來,也讓知識點(diǎn)在腦海里能形成一個(gè)體系。
開發(fā)環(huán)境
idea2016、mybatis3、SQLServer2012
pom.xml、mybatis.xml、log4j.properties
先貼上pom.xml是因?yàn)樗苯雍痛罱ㄩ_發(fā)環(huán)境和測試環(huán)境有關(guān)系,mybatis.xml則是連接數(shù)據(jù)庫,log4j.properties在學(xué)習(xí)階段配置上有助于我們觀察SQL的執(zhí)行情況。
1、pom.xml
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
2、mybatis.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> <!-- MyBatis針對SqlServer進(jìn)行的配置 --> <typeAliases> <typeAlias alias="User" type="com.autohome.model.User"/> <typeAlias alias="Teacher" type="com.autohome.model.Teacher" /> <typeAlias alias="Student" type="com.autohome.model.Student" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/> <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=test"/> <property name="username" value="sa"/> <property name="password" value="0"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/User.xml"/> <mapper resource="mapper/Student.xml"/> </mappers> </configuration>
3、log4j.properties
### Log4j配置 ### ### 與Spring結(jié)合需要在web.xml中指定此文件位置,并添加監(jiān)聽器 ### #定義log4j的輸出級別和輸出目的地(目的地可以自定義名稱,和后面的對應(yīng)) #[ level ] , appenderName1 , appenderName2 log4j.rootLogger=DEBUG,console,file #-----------------------------------# #1 定義日志輸出目的地為控制臺 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG ####可以靈活地指定日志輸出格式,下面一行是指定具體的格式 ### #%c: 輸出日志信息所屬的類目,通常就是所在類的全名 #%m: 輸出代碼中指定的消息,產(chǎn)生的日志具體信息 #%n: 輸出一個(gè)回車換行符,Windows平臺為"/r/n",Unix平臺為"/n"輸出日志信息換行 log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n #-----------------------------------# #2 文件大小到達(dá)指定尺寸的時(shí)候產(chǎn)生一個(gè)新的文件 log4j.appender.file = org.apache.log4j.RollingFileAppender #日志文件輸出目錄 log4j.appender.file.File=log/tibet.log #定義文件最大大小 log4j.appender.file.MaxFileSize=10mb ###輸出日志信息### #最低級別 log4j.appender.file.Threshold=ERROR log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #-----------------------------------# #3 druid log4j.logger.druid.sql=INFO log4j.logger.druid.sql.DataSource=info log4j.logger.druid.sql.Connection=info log4j.logger.druid.sql.Statement=info log4j.logger.druid.sql.ResultSet=info #4 mybatis 顯示SQL語句部分 log4j.logger.org.mybatis=DEBUG #log4j.logger.cn.tibet.cas.dao=DEBUG #log4j.logger.org.mybatis.common.jdbc.SimpleDataSource=DEBUG# #log4j.logger.org.mybatis.common.jdbc.ScriptRunner=DEBUG# #log4j.logger.org.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG# #log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
配置mapper.xml
mapper.xml在mybatis.xml是專職處理sql的一個(gè)環(huán)節(jié),各種映射和實(shí)現(xiàn)都在這里處理
<?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.autohome.mapper.User"> <!-- 查詢?nèi)坑脩?--> <select id="queryUsers" resultType="com.autohome.model.User"> select * from t_userinfo </select> <!-- 按照ID查詢 --> <select id="queryUserById" parameterType="int" resultType="com.autohome.model.User"> select * from t_userinfo where id=#{id} </select> <select id="queryUserByAddress" resultType="com.autohome.model.User"> select * from t_userinfo where name=#{name,javaType=String,jdbcType=VARCHAR} and address=#{address} </select> <!-- 添加用戶 --> <insert id="insertUsers" parameterType="com.autohome.model.User"> insert into t_userinfo (name,address) values(#{name},#{address}) </insert> <!-- 修改用戶 --> <update id="updateUsers" parameterType="com.autohome.model.User"> update t_userinfo set name=#{name},address=#{address} where id=#{id} </update> <!-- 刪除用戶 --> <delete id="deleteUsers" parameterType="int"> delete t_userinfo where id=#{id} </delete> </mapper>
建立單元測試
1、準(zhǔn)備工作,我建立的是控制臺程序,所以在使用sqlsession前先創(chuàng)建sqlsessionfactory。當(dāng)然,還要加載log4j.properties
SqlSessionFactory sqlSessionFactory=null; @Before public void BeforeClass(){ try { InputStream is=Resources.getResourceAsStream("log4j.properties"); PropertyConfigurator.configure(is); Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } }
2、queryUsers
@Test public void queryUsers() throws Exception { //線程不安全類型,放在方法體內(nèi) SqlSession sqlSession=null; try { sqlSession=sqlSessionFactory.openSession(); List<User> list = sqlSession.selectList("com.autohome.mapper.User.queryUsers"); System.out.println("size:"+list.size()); } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } }
3、queryUserById
@Test public void queryUserById() { SqlSession sqlSession=null; try{ sqlSession=sqlSessionFactory.openSession(); User user = sqlSession.selectOne("com.autohome.mapper.User.queryUserById",2); System.out.println("id:"+user.getId()+",name:"+user.getName()+","+user.getAddress()); }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
4、insertUser
@Test public void insertUser(){ SqlSession sqlSession=null; try{ sqlSession=sqlSessionFactory.openSession(); User user =new User(); user.setName("kobe"); user.setAddress("usa"); int result = sqlSession.insert("com.autohome.mapper.User.insertUsers",user); sqlSession.commit(); if(result>0){ System.out.println("insert success...."); }else{ System.out.println("insert error...."); } }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
5、updateUser
@Test public void updateUser(){ SqlSession sqlSession=null; try{ sqlSession=sqlSessionFactory.openSession(); User user =new User(); user.setId(36); user.setName("kobe"); user.setAddress("usa"); int result = sqlSession.update("com.autohome.mapper.User.updateUsers",user); sqlSession.commit(); if(result>0){ System.out.println("update success...."); }else{ System.out.println("update error...."); } }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
6、deleteUser
@Test public void deleteUser(){ SqlSession sqlSession=null; try{ sqlSession=sqlSessionFactory.openSession(); int result = sqlSession.delete("com.autohome.mapper.User.deleteUsers",49); sqlSession.commit(); if(result>0){ System.out.println("delete success...."); }else{ System.out.println("delete error...."); } }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
總結(jié)
添加、修改、刪除的操作要調(diào)用sqlsession.commit(),不然數(shù)據(jù)無法入庫的,我剛開始就忘記了這個(gè)。
以上所述是小編給大家介紹的MyBatis中SqlSession實(shí)現(xiàn)增刪改查案例,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時(shí)回復(fù)大家的!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。