Mybatis—注解開發

Mybatis的注解開發

MyBatis的常用注解

這幾年來注解開發越來越流行,Mybatis也可以使用注解開發方式,這樣我們就可以減少編寫Mapper映射文件了。

@Insert:實現新增

@Update:實現更新

@Delete:實現刪除

@Select:實現查詢

@Result:實現結果集封裝

@Results:可以與@Result 一起使用,封裝多個結果集

@One:實現一對一結果集封裝

@Many:實現一對多結果集封裝

MyBatis的增刪改查

我們完成簡單的user表的增刪改查的操作
修改MyBatis的核心配置文件,我們使用了注解替代的映射文件,所以我們只需要加載使用了注解的Mapper接口即可

<mappers><!--掃描使用注解的類--><mapper class="com.itheima.mapper.UserMapper"></mapper>
</mappers>

或者指定掃描包含映射關系的接口所在的包也可以

<mappers><!--掃描使用注解的類所在的包--><package name="com.itheima.mapper"></package>
</mappers>
    userMapper mapper;@Beforepublic void before(){InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");} catch (IOException ioException) {ioException.printStackTrace();}SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);mapper = sqlSession.getMapper(userMapper.class);}@Testpublic void tset4() {User user = new User();user.setUsername("cx");user.setPassword("159");mapper.add(user);}@Testpublic void tset5() {mapper.delete(5);}@Testpublic void tset6() {User user = new User();user.setId(4);user.setPassword("159");mapper.update(user);}@Testpublic void tset7() {System.out.println(mapper.findById(1));}
public interface userMapper {@Select(" select * from  user")public List<User> findAll();@Select("select * from  user where id=#{id}")public User findById(int i);@Insert(" insert into user values (#{id},#{username},#{password},#{birthday})")public void add(User user);@Update(" update user set password=#{password} where id=#{id}")public void update(User user);@Delete("delete from user where id=#{id}")public void delete(int i);}

MyBatis的注解實現復雜映射開發

實現復雜關系映射之前我們可以在映射文件中通過配置來實現,使用注解開發后,我們可以使用@Results注解,@Result注解,@One注解,@Many注解組合完成復雜關系的配置

一對一查詢

一對一查詢的模型

用戶表和訂單表的關系為,一個用戶有多個訂單,一個訂單只從屬于一個用戶

一對一查詢的需求:查詢一個訂單,與此同時查詢出該訂單所屬的用戶

創建Order和User實體
public class Order {private int id;private Date ordertime;private double total;//代表當前訂單從屬于哪一個客戶private User user;
}public class User {private int id;private String username;private String password;private Date birthday;}
創建OrderMapper接口
public interface OrderMapper {List<Order> findAll();
}
使用注解配置Mapper
public interface OrderMapper {@Select("select * from orders")@Results({@Result(property = "id",column = "id"),@Result(property = "ordertime",column = "ordertime"),@Result(property = "total",column = "total"),@Result(property = "user",column = "uid",javaType = User.class,one =@One(select = "com.controller.userMapper.findById"))})List<Order> findAll();
}
測試結果
    @Testpublic void tset3() {InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");} catch (IOException ioException) {ioException.printStackTrace();}SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);System.out.println(mapper.findAll());}

一對多查詢

一對多查詢的模型

用戶表和訂單表的關系為,一個用戶有多個訂單,一個訂單只從屬于一個用戶

一對多查詢的需求:查詢一個用戶,與此同時查詢出該用戶具有的訂單

修改User實體
public class Order {private int id;private Date ordertime;private double total;//代表當前訂單從屬于哪一個客戶private User user;
}public class User {private int id;private String username;private String password;private Date birthday;//代表當前用戶具備哪些訂單private List<Order> orderList;
}
創建UserMapper接口
List<User> findAllUserAndOrder();
使用注解配置Mapper
    @Select( "select * from user")@Results({@Result(property = "username" ,column = "username"),@Result(property = "password",column = "password"),@Result(property = "birthday" ,column = "birthday"),@Result(id=true,property = "id",column = "id"),@Result(property = "orderList",column = "id",javaType = List.class,many = @Many(select = "com.controller.OrderMapper.findByUid"))})public  List<User> findAllUserAndOrder();
    @Select("select * from  orders where uid=#{uid}")Order findByUid(int i);
測試結果
    userMapper mapper;@Beforepublic void before(){InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");} catch (IOException ioException) {ioException.printStackTrace();}SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);mapper = sqlSession.getMapper(userMapper.class);}  @Testpublic void tset7() {System.out.println(mapper.findAllUserAndOrder());}

多對多查詢

多對多查詢的模型

用戶表和角色表的關系為,一個用戶有多個角色,一個角色被多個用戶使用

多對多查詢的需求:查詢用戶同時查詢出該用戶的所有角色

public class User {private int id;private String username;private String password;private Date birthday;//代表當前用戶具備哪些訂單private List<Order> orderList;//代表當前用戶具備哪些角色private List<Role> roleList;
}public class Role {private int id;private String rolename;}
添加UserMapper接口方法
List<User> findAllUserAndRole();
使用注解配置Mapper
    @Select( "select * from user")@Results({@Result(property = "username" ,column = "username"),@Result(property = "password",column = "password"),@Result(property = "birthday" ,column = "birthday"),@Result(id=true,property = "id",column = "id"),@Result(property = "roleList",column = "id",javaType = List.class,many = @Many(select = "com.controller.RoleMapper.findById"))})public  List<User> findAllUserAndRole();
public interface RoleMapper {@Select("select r.* from sys_user_role ur,sys_role r where ur.roleid=r.id and #{id}=ur.userid")List<Role> findById(int i);
}
測試結果
    @Beforepublic void before(){InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");} catch (IOException ioException) {ioException.printStackTrace();}SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);mapper = sqlSession.getMapper(userMapper.class);}@Testpublic void tset7() {System.out.println(mapper.findAllUserAndRole());}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391794.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391794.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391794.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

道路工程結構計算軟件_我從軟件工程到產品管理的道路

道路工程結構計算軟件by Sari Harrison莎莉哈里森(Sari Harrison) 我從軟件工程到產品管理的道路 (My path from software engineering to product management) 以及一些有關如何自己做的建議 (And some advice on how to do it yourself) I am often asked how to make the m…

Vue 指令

下面列舉VUE的HTML頁面模板指令&#xff0c;并進行分別練習。 1. templates 2. v-if, v-for <div idapp><ol><li v-for"todo in todos>{{ todo.text}}</li></ol> </div><script>app new Vue({ el: #app, data: { return…

iOS-FMDB

2019獨角獸企業重金招聘Python工程師標準>>> #import <Foundation/Foundation.h> #import <FMDatabase.h> #import "MyModel.h"interface FMDBManager : NSObject {FMDatabase *_dataBase; }(instancetype)shareInstance;- (BOOL)insert:(MyM…

解決朋友圈壓縮_朋友中最有趣的朋友[已解決]

解決朋友圈壓縮We live in uncertain times.我們生活在不確定的時代。 We don’t know when we’re going back to school or the office. We don’t know when we’ll be able to sit inside at a restaurant. We don’t even know when we’ll be able to mosh at a Korn co…

西安項目分析

西安物流 西安高考補習 西安藝考 轉載于:https://www.cnblogs.com/wpxuexi/p/7294269.html

MapServer應用開發平臺示例

MapServer為當前開源WebGIS的應用代表&#xff0c;在西方社會應用面極為廣泛&#xff0c;現介紹幾個基于它的開源應用平臺。 1.GeoMOOSE GeoMoose is a Web Client Javascript Framework for displaying distributed cartographic data. Among its many strengths, it can hand…

leetcode 995. K 連續位的最小翻轉次數(貪心算法)

在僅包含 0 和 1 的數組 A 中&#xff0c;一次 K 位翻轉包括選擇一個長度為 K 的&#xff08;連續&#xff09;子數組&#xff0c;同時將子數組中的每個 0 更改為 1&#xff0c;而每個 1 更改為 0。 返回所需的 K 位翻轉的最小次數&#xff0c;以便數組沒有值為 0 的元素。如果…

kotlin數據庫_如何在Kotlin應用程序中使用Xodus數據庫

kotlin數據庫I want to show you how to use one of my favorite database choices for Kotlin applications. Namely, Xodus. Why do I like using Xodus for Kotlin applications? Well, here are a couple of its selling points:我想向您展示如何在Kotlin應用程序中使用我…

使用route add添加路由,使兩個網卡同時訪問內外網

route add命令格式&#xff1a;route [-f] [-p] [Command] [Destination] [mask Netmask] [Gateway] [metric Metric] [if Interface] 通過配置電腦的靜態路由來實現同時訪問內外網的。電腦的網絡IP配置不用變&#xff0c;兩個網卡都按照正常配置&#xff08;都配置IP地址、子網…

基于JavaConfig配置的Spring MVC的構建

上一篇講了基于XML配置的構建&#xff0c;這一篇講一講基于JavaConfig的構建。為什么要寫這篇文章&#xff0c;因為基于xml配置的構建&#xff0c;本人認為很麻煩&#xff0c;要寫一堆的配置&#xff0c;不夠簡潔&#xff0c;而基于JavacConfig配置的構建符合程序員的編碼習慣&…

pymc3 貝葉斯線性回歸_使用PyMC3進行貝葉斯媒體混合建模,帶來樂趣和收益

pymc3 貝葉斯線性回歸Michael Johns, Zhenyu Wang, Bruno Dupont, and Luca Fiaschi邁克爾約翰斯&#xff0c;王振宇&#xff0c;布魯諾杜邦和盧卡菲亞斯基 “If you can’t measure it, you can’t manage it, or fix it”“如果無法衡量&#xff0c;就無法管理或修復它” –…

webkit中對incomplete type指針的處理技巧

近日在研究webkit的時候發現了一個函數 template<typename T> inline void deleteOwnedPtr(T* ptr) {typedef char known[sizeof(T) ? 1 : -1];if(sizeof(known))delete ptr; } 一開始對這個函數非常費解&#xff0c;為什么作者不直接 delete ptr; 通過上stackoverflow提…

leetcode 1004. 最大連續1的個數 III(滑動窗口)

給定一個由若干 0 和 1 組成的數組 A&#xff0c;我們最多可以將 K 個值從 0 變成 1 。 返回僅包含 1 的最長&#xff08;連續&#xff09;子數組的長度。 示例 1&#xff1a; 輸入&#xff1a;A [1,1,1,0,0,0,1,1,1,1,0], K 2 輸出&#xff1a;6 解釋&#xff1a; [1,1,1…

我如何找到工作并找到理想的工作

By Julius Zerwick朱利葉斯澤威克(Julius Zerwick) This article is about how I went through my job hunt for a full time position as a software engineer in New York City and ended up with my dream job. I had spent two years building my skills and had aspirati…

synchronized 與 Lock 的那點事

synchronized 與 Lock 的那點事 最近在做一個監控系統&#xff0c;該系統主要包括對數據實時分析和存儲兩個部分&#xff0c;由于并發量比較高&#xff0c;所以不可避免的使用到了一些并發的知識。為了實現這些要求&#xff0c;后臺使用一個隊列作為緩存&#xff0c;對于請求只…

ols線性回歸_普通最小二乘[OLS]方法使用于機器學習的簡單線性回歸變得容易

ols線性回歸Hello Everyone!大家好&#xff01; I am super excited to be writing another article after a long time since my previous article was published.自從上一篇文章發表很長時間以來&#xff0c;我很高興能寫另一篇文章。 A Simple Linear Regression [SLR] is…

ubuntu安裝配置jdk

先去 Oracle下載Linux下的JDK壓縮包&#xff0c;我下載的是jdk-7u4-linux-i586.tar.gz文件&#xff0c;下好后直接解壓Step1:# 將解壓好的jdk1.7.0_04文件夾用最高權限復制到/usr/lib/jvm目錄里sudo cp -r ~/jdk1.7.0_04/ /usr/lib/jvm/Step2:# 配置環境變量sudo gedit ~/.prof…

leetcode 697. 數組的度(hashmap)

給定一個非空且只包含非負數的整數數組 nums&#xff0c;數組的度的定義是指數組里任一元素出現頻數的最大值。 你的任務是在 nums 中找到與 nums 擁有相同大小的度的最短連續子數組&#xff0c;返回其長度。 示例 1&#xff1a; 輸入&#xff1a;[1, 2, 2, 3, 1] 輸出&…

facebook機器學習_如何為您的頁面創建Facebook Messenger機器人

facebook機器學習by Paul Pinard保羅皮納德(Paul Pinard) 如何為您的頁面創建Facebook Messenger機器人 (How to create a Facebook messenger bot for your page) When it comes to sharing your chatbot, Facebook Messenger is a must. We created a very easy step-by-ste…

Logstash配置語法及相關命令

配置結構以及插件位置 輸入插件&#xff1a; input{ … } 過濾插件&#xff1a; filter{ … } 輸出插件&#xff1a; output{ … } 數據類型 - Array users > [{id > 1,name > N1},{id > 2,name > N2}] - lists path > ["/var/log/messages"…