MyBatis實例
應用MyBatis來實現簡單的增刪改查,下面分別實現:
對象類如下:
1 public class User {
2 private int id;
3 private String username;// 用戶姓名
4 private String sex;// 性別
5 private Date birthday;// 生日
6 private String address;// 地址
7 public int getId() {
8 return id;
9 }
10 public void setId(int id) {
11 this.id = id;
12 }
13 public String getUsername() {
14 return username;
15 }
16 public void setUsername(String username) {
17 this.username = username;
18 }
19 public String getSex() {
20 return sex;
21 }
22 public void setSex(String sex) {
23 this.sex = sex;
24 }
25 public Date getBirthday() {
26 return birthday;
27 }
28 public void setBirthday(Date birthday) {
29 this.birthday = birthday;
30 }
31 public String getAddress() {
32 return address;
33 }
34 public void setAddress(String address) {
35 this.address = address;
36 }
37 @Override
38 public String toString() {
39 // TODO Auto-generated method stub
40 return this.id+"-"+this.username+"-"+this.sex+"-"+this.address+"-"+this.birthday.toString();
41 }
42
43 }
View Code
SqlMapConfig.xml配置如下:
1 <configuration>
2 <!-- 和spring整合後 environments配置將廢除-->
3 <environments default="development">
4 <environment id="development">
5 <!-- 使用jdbc事務管理-->
6 <transactionManager type="JDBC" />
7 <!-- 資料庫連接池-->
8 <dataSource type="POOLED">
9 <property name="driver" value="com.mysql.jdbc.Driver" />
10 <property name="url" value="jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8" />
11 <property name="username" value="root" />
12 <property name="password" value="" />
13 </dataSource>
14 </environment>
15 </environments>
16 <mappers>
17 <mapper resource="sqlmap/User.xml"/>
18 </mappers>
19 </configuration>
View Code
1、用戶id查詢一個用戶信息
映射文件如下:
1 <mapper namespace="user">
2 <select id="findUserById" parameterType="int" resultType="com.luchao.mybatis.first.po.User">
3 select * from user where id = #{id}
4 </select>
5 </mapper>
注意:namespace :命名空間,對sql進行分類化管理,用於隔離sql語句。
id:和namespace 一起標識statement。
parameterType:定義輸入到sql中的映射類型,#{id}表示使用preparedstatement設置佔位符號並將輸入變量id傳到sql。
resultType:定義結果映射類型。
代碼:
1 @Before
2 public void createSqlSessionFactory() throws IOException{
3 //配置文件
4 String resource = "SqlMapConfig.xml";
5 InputStream inputStream = Resources.getResourceAsStream(resource);
6 //使用SqlSessionFactoryBuilder從xml配置文件中加載sqlSessionFactory
7 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
8 }
9 //根據id查詢用戶
10 @Test
11 public void findUserByIdTest(){
12 //資料庫會話實例
13 SqlSession session = null;
14 try {
15 // 創建資料庫會話實例sqlSession
16 session = sqlSessionFactory.openSession();
17 // 查詢單個記錄,根據用戶id查詢用戶信息
18 User user = session.selectOne("user.findUserById", 10);
19 System.out.println(user);
20 } catch (Exception e) {
21 // TODO Auto-generated catch block
22 e.printStackTrace();
23 } finally{
24 if(session!=null){
25 session.close();
26 }
27 }
28 }
2、根據用戶名模糊查詢用戶信息
映射文件:
1 <select id="findUserByName" parameterType="java.lang.String" resultType="com.luchao.mybatis.first.po.User">
2 select * from user where username like '%${value}%'
3 </select>
#{}表示一個佔位符號,通過#{}可以實現preparedStatement向佔位符中設置值,自動進行java類型和jdbc類型轉換,#{}可以有效防止sql注入。 #{}可以接收簡單類型值或pojo屬性值。 如果parameterType傳輸單個簡單類型值,#{}括號中可以是value或其它名稱。
${}表示拼接sql串,通過${}可以將parameterType 傳入的內容拼接在sql中且不進行jdbc類型轉換, ${}可以接收簡單類型值或pojo屬性值,如果parameterType傳輸單個簡單類型值,${}括號中只能是value。
代碼:
1 //根據用戶名模糊查詢用戶
2 @Test
3 public void findUserByNameTest(){
4 //資料庫會話實例
5 SqlSession session = null;
6 try {
7 // 創建資料庫會話實例sqlSession
8 session = sqlSessionFactory.openSession();
9 // 查詢多個記錄,根據用戶姓名模糊查詢用戶信息
10 List<User> userList = session.selectList("user.findUserByName", "張");
11 System.out.println(userList.size());
12 } catch (Exception e) {
13 // TODO Auto-generated catch block
14 e.printStackTrace();
15 } finally{
16 if(session!=null){
17 session.close();
18 }
19 }
20 }
selectOne查詢一條記錄,如果使用selectOne查詢多條記錄則拋出異常:
1 org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3
2 at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)
selectList可以查詢一條或多條記錄。
3、添加用戶
映射文件:
1 <insert id="insertUser" parameterType="com.luchao.mybatis.first.po.User">
2 <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
3 select LAST_INSERT_ID()
4 </selectKey>
5 insert into user(username,birthday,sex,address) value (#{username},#{birthday},#{sex},#{address});
6 </insert>
這裡要注意,如果mysql是自增主鍵,映射文件如下:
1 insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
2 <!-- selectKey將主鍵返回,需要再返回 -->
3 <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
4 select LAST_INSERT_ID()
5 </selectKey>
6 insert into user(username,birthday,sex,address)
7 values(#{username},#{birthday},#{sex},#{address});
8 </insert>
添加selectKey實現將主鍵返回
keyProperty:返回的主鍵存儲在pojo中的哪個屬性
order:selectKey的執行順序,是相對與insert語句來說,由於mysql的自增原理執行完insert語句之後才將主鍵生成,所以這裡selectKey的執行順序為after
resultType:返回的主鍵是什麼類型
LAST_INSERT_ID():是mysql的函數,返回auto_increment自增列新記錄id值。
mysql是UUID實現,映射文件如下:
1 <insert id="insertUser" parameterType="cn.luchao.mybatis.po.User">
2 <selectKey resultType="java.lang.String" order="BEFORE"
3 keyProperty="id">
4 select uuid()
5 </selectKey>
6 insert into user(id,username,birthday,sex,address)
7 values(#{id},#{username},#{birthday},#{sex},#{address})
8 </insert>
9 注意這裡使用的order是「BEFORE」
Oracle使用序列實現,映射文件如下:
1 <insert id="insertUser" parameterType="cn.luchao.mybatis.po.User">
2 <selectKey resultType="java.lang.Integer" order="BEFORE"
3 keyProperty="id">
4 SELECT 自定義序列.NEXTVAL FROM DUAL
5 </selectKey>
6 insert into user(id,username,birthday,sex,address)
7 values(#{id},#{username},#{birthday},#{sex},#{address})
8 </insert>
9 注意這裡使用的order是「BEFORE」
代碼:
1 //插入用戶
2 @Test
3 public void insertUserTest(){
4 //資料庫會話實例
5 SqlSession session = null;
6 try {
7 // 創建資料庫會話實例sqlSession
8 session = sqlSessionFactory.openSession();
9 //添加用戶信息
10 User user = new User();
11 user.setAddress("上海");
12 user.setBirthday(new Date());
13 user.setSex("1");
14 user.setUsername("王小二");
15 session.insert("insertUser",user);
16 //提交事務
17 session.commit();
18 } catch (Exception e) {
19 // TODO Auto-generated catch block
20 e.printStackTrace();
21 } finally{
22 if(session!=null){
23 session.close();
24 }
25 }
26 }
4、刪除用戶
映射文件:
1 <delete id="deleteUser" parameterType="int">
2 delete from user where id=#{id}
3 </delete>
代碼:
1 //刪除用戶
2 @Test
3 public void deleteUserTest(){
4 //資料庫會話實例
5 SqlSession session = null;
6 try {
7 // 創建資料庫會話實例sqlSession
8 session = sqlSessionFactory.openSession();
9 session.delete("deleteUser",30);
10 //提交事務
11 session.commit();
12 } catch (Exception e) {
13 // TODO Auto-generated catch block
14 e.printStackTrace();
15 } finally{
16 if(session!=null){
17 session.close();
18 }
19 }
20 }
5、修改用戶:
映射文件:
1 <update id="updateUser" parameterType="com.luchao.mybatis.first.po.User">
2 update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
3 where id=#{id}
4 </update>
代碼:
1 //修改用戶
2 @Test
3 public void updteaUserTest(){
4 //資料庫會話實例
5 SqlSession session = null;
6 try {
7 // 創建資料庫會話實例sqlSession
8 session = sqlSessionFactory.openSession();
9 //修改用戶信息
10 User user = new User();
11 user.setId(28);
12 user.setAddress("上海");
13 user.setBirthday(new Date());
14 user.setSex("0");
15 user.setUsername("王小二1");
16 session.update("updateUser", user);
17 //提交事務
18 session.commit();
19 } catch (Exception e) {
20 // TODO Auto-generated catch block
21 e.printStackTrace();
22 } finally{
23 if(session!=null){
24 session.close();
25 }
26 }
27 }
MyBatis解決JDBC編程的問題
1、 資料庫連結創建、釋放頻繁造成系統資源浪費從而影響系統性能,如果使用資料庫連結池可解決此問題。
解決:在SqlMapConfig.xml中配置數據連結池,使用連接池管理資料庫連結。
2、 Sql語句寫在代碼中造成代碼不易維護,實際應用sql變化的可能較大,sql變動需要改變java代碼。
解決:將Sql語句配置文件中與java代碼分離。
3、 向sql語句傳參數麻煩,因為sql語句的where條件不一定,可能多也可能少,佔位符需要和參數一一對應。
解決:Mybatis自動將java對象映射至sql語句,通過statement中的parameterType定義輸入參數的類型。
4、 對結果集解析麻煩,sql變化導致解析代碼變化,且解析前需要遍歷,如果能將資料庫記錄封裝成pojo對象解析比較方便。
解決:Mybatis自動將sql執行結果映射至java對象,通過statement中的resultType定義輸出結果的類型。
來源:網絡。若涉及版權問題,煩請原作者聯繫我們,我們會在24小時內刪除處理,謝謝!
中軟高科
微信號:javaedu
(長按上圖,彈出「識別二維碼」後可快速關注)