mybatis实现一对多连接查询
底层数据库为postgresql,ORM框架为mybatis。
关键代码如下:
mybatis配置文件如下:
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>
- <settings>
- <setting name="cacheEnabled" value="true" />
- <setting name="lazyLoadingEnabled" value="true" />
- <setting name="multipleResultSetsEnabled" value="true" />
- <setting name="useColumnLabel" value="true" />
- <setting name="useGeneratedKeys" value="true" />
- <setting name="defaultExecutorType" value="SIMPLE" />
- <setting name="defaultStatementTimeout" value="25000" />
- </settings>
- <typeAliases>
- <typeAlias type="com.mybatis.domain.User" alias="User" />
- <typeAlias type="com.mybatis.domain.Score" alias="Score" />
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="org.postgresql.Driver" />
- <property name="url" value="jdbc:postgresql://localhost:5432/mybatis" />
- <property name="username" value="postgres" />
- <property name="password" value="admin" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="com/mybatis/domain/User.xml" />
- <mapper resource="com/mybatis/domain/Score.xml" />
- </mappers>
- </configuration>
User.java代码为:
- package com.mybatis.domain;
- public class User {
- private Integer id;//用户id
- private String username;//用户名
- private String password;//密码
- private String address;//地址
- public User(){
- }
- public User(String username,String password,String address){
- this.username = username;
- this.password = password;
- this.address =address;
- }
- public User(Integer id,String username,String password,String address){
- this.id = id;
- this.username = username;
- this.password = password;
- this.address =address;
- }
- public int getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public String toString(){
- return "当前用户为:id = "+id+",username = "+username+",password = "+password+",address = "+address;
- }
- }
Score.java代码如下:
- package com.mybatis.domain;
- public class Score {
- private Integer id ;//主键id
- private User user;//所属用户
- private int math ;//数学成绩
- private int chinese ;//语文成绩
- private int english ;//英语成绩
- private int computer ;//计算机成绩
- public Score(){
- }
- public Score(User user, int math,int chinese,int english,int computer){
- this.user = user;
- this.math = math;
- this.chinese = chinese;
- this.english = english;
- this.computer = computer;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public int getMath() {
- return math;
- }
- public void setMath(int math) {
- this.math = math;
- }
- public int getChinese() {
- return chinese;
- }
- public void setChinese(int chinese) {
- this.chinese = chinese;
- }
- public int getEnglish() {
- return english;
- }
- public void setEnglish(int english) {
- this.english = english;
- }
- public int getComputer() {
- return computer;
- }
- public void setComputer(int computer) {
- this.computer = computer;
- }
- public String toString(){
- return "id = "+ this.id+",math = "+this.math+",chinese = "+this.chinese+",english = "+this.english+",computer = "+this.computer+
- ", userid = "+this.user.getId()+",username = "+this.user.getUsername()+",password = "+this.user.getPassword()+
- ",address = "+this.user.getAddress();
- }
- }
user.xml中的关键代码为:
- <resultMap type="User" id="userResult">
- <id property="id" column="userid"/>
- <result property="username" column="username"/>
- <result property="password" column="password"/>
- <result property="address" column="address"/>
- </resultMap>
这里的对象的属性id对应的数据库表列名为userid,这是user对象为pg_score表中
的标示。
score.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="ScoreDaoMapping">
- <resultMap type="Score" id="score">
- <constructor>
- <idArg column="id" javaType="int" />
- <arg column="userid" javaType="int" />
- <arg column="math" javaType="int" />
- <arg column="chinese" javaType="int" />
- <arg column="english" javaType="int" />
- <arg column="computer" javaType="int" />
- </constructor>
- </resultMap>
- <resultMap id="joinSelectScore" type="Score" >
- <id property="id" column="id"/>
- <result property="math" column="math"/>
- <result property="chinese" column="chinese"/>
- <result property="english" column="english"/>
- <result property="computer" column="computer"/>
- <association property="user" column="userid" javaType="User" resultMap="UserDaoMapping.userResult"/>
- </resultMap>
- <insert id="insertScore" parameterType="Score">
- insert into pg_score(math,chinese,english,computer,userid) values(#{math},#{chinese},#{english},#{computer},#{user.id})
- </insert>
- <select id="findScoreByUser" resultMap="joinSelectScore" resultType="list" parameterType="map">
- select
- s.id as id,
- s.math as math,
- s.chinese as chinese,
- s.english as english,
- s.computer as computer,
- u.id as userid,
- u.username as username,
- u.password as password,
- u.address as address
- from pg_score s left outer join pg_userinfo u on s.userid = u.id where u.id=#{userid}
- </select>
- </mapper>
ScoreDao.java中的关键代码为:
- private String resource = "com/mybatis/configuration/mybatis.xml";
- public List<Score> selectScoreByUser(User user) throws IOException{
- Reader reader = Resources.getResourceAsReader(resource);
- SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
- SqlSession session = ssf.openSession();
- reader.close();
- Map<String,Integer> params = new HashMap<String,Integer>();
- params.put("userid", user.getId());
- List<Score> scoreList = session.selectList("ScoreDaoMapping.findScoreByUser", params);
- session.commit();
- session.close();
- return scoreList;
- }
ScoreService.java代码如下:
- package com.mybatis.service;
- import java.io.IOException;
- import java.util.List;
- import com.mybatis.dao.ScoreDao;
- import com.mybatis.domain.Score;
- import com.mybatis.domain.User;
- public class ScoreService {
- private ScoreDao scoreDao = new ScoreDao();
- public ScoreDao getScoreDao() {
- return scoreDao;
- }
- public void setScoreDao(ScoreDao scoreDao) {
- this.scoreDao = scoreDao;
- }
- public List<Score> getScoreByUser(User user) throws IOException{
- return scoreDao.selectScoreByUser(user);
- }
- public void insertScore(Score score) throws IOException{
- scoreDao.insert(score);
- }
- }
Test.java代码如下:
- package com.mybatis.test;
- import java.util.List;
- import com.mybatis.domain.Score;
- import com.mybatis.domain.User;
- import com.mybatis.service.ScoreService;
- import com.mybatis.service.UserService;
- public class Test {
- private UserService userService = new UserService();
- private ScoreService scoreSerice = new ScoreService();
- public static void main(String[] args) throws Exception{
- Test test = new Test();
- //test.insertScore();
- List<Score> scoreList = test.getScore();
- Score score = null;
- for(int i=0;i<scoreList.size();i++){
- System.out.println("第"+(i+1)+"个score对象为:");
- score = scoreList.get(i);
- System.out.println(score);
- }
- }
- public void insertScore() throws Exception{
- List<User> userList = userService.getPageUsers(10, 0);
- User user = userList.get(2);
- Score score = new Score();
- score.setUser(user);
- score.setChinese(80);
- score.setComputer(90);
- score.setEnglish(91);
- score.setMath(98);
- scoreSerice.insertScore(score);
- }
- public List<Score> getScore() throws Exception{
- List<User> userList = userService.getPageUsers(10, 0);
- User user = userList.get(0);
- List<Score> scoreList = scoreSerice.getScoreByUser(user);
- return scoreList;
- }
- /* public User getUserById(int id) throws Exception{
- return userService.getUserById(id);
- }*/
- }
mybatis实现一对多连接查询的更多相关文章
- mybatis 13: 一对多关联查询
业务背景 根据客户id查询客户基本信息,以及客户存在的订单信息 两张数据表 客户表 订单表 实体类 客户实体类:Customer private Integer id; private String ...
- MyBatis:一对多关联查询
MyBatis从入门到放弃四:一对多关联查询 前言 上篇学习了一对一关联查询,这篇我们学习一对多关联查询.一对多关联查询关键点则依然是配置resultMap,在resultMap中配置collecti ...
- mybatis collection 一对多关联查询,单边分页的问题总结!
若想直接通过sql实现多级关联查询表结构得有2 个必不可少的字段:id ,parentId,levelId id:主键id, parentId:父id levelId:表示第几级(表本身关联查询的时候 ...
- 使用mybatis进行一对多嵌套查询时出错:输出结果:Country{id=2, name='美国', minister=[null]}
即Minister类作为Country类的关联属性. 查询的输出结果是:Country{id=2, name='美国', minister=[null]} <!--mapper.xml内容--& ...
- mybatis处理一对多的查询
//查询出某个班级对应的所有老师和学生 1.使用嵌套结果 <select id="findClasses3" parameterType="int" re ...
- Mybatis中的多表查询 多对一,一对多
示例:用户和账户 一个用户可以有多个账户 一个账户只能属于一个用户(多个账户也可以属于同一个用户) 步骤: 1.建立两张表:用户表,账户表 让用户表和账户表之间具备一对多的关系:需要使用外键在账户表中 ...
- MyBatis数据持久化(七)多表连接查询
本节继续以多表连接查询的案例介绍使用resultMap的好处,对于两张以上的表进行关联查询,当我们有选择的从不同表查询所需字段时,使用resultMap是相当方便的.例如我们有两张表,分别为用户表Us ...
- 7.mybatis一对多关联查询
和第5节一对一查询类似,但是不同的是,一对一使用的是association,而一对多使用collection. 实例: 1个班级Class,对应1个老师Teacher,对应多个学生Student 1. ...
- MyBatis从入门到放弃四:一对多关联查询
前言 上篇学习了一对一关联查询,这篇我们学习一对多关联查询.一对多关联查询关键点则依然是配置resultMap,在resultMap中配置collection属性,别忽略了ofType属性. 搭建开发 ...
随机推荐
- iproute2 对决 net-tools
如今很多系统管理员依然通过组合使用诸如ifconfig.route.arp和netstat等命令行工具(统称为net-tools)来配置网络功能,解决网络故障.net-tools起源于BSD的TCP/ ...
- linux系统配置jdk环境
前提:linux服务器+JDK8-linux版本 工具:FileZilla+Xshell 将jdk上传到服务器的某个文件夹(本人是JDK) 进入该文件夹,输入tar xzvf jdk-8u77-li ...
- 针对开发项目的NABCD的分析
N(Need需求) 我们的创意是用户登录我们的软件,就可以实现自己修改图片,添加文字.解决了目前用户不知道如何P图,如何添加文字的难题. A(Approach做法) 我们的团队将用VS软件开发一个修改 ...
- selenium元素定位Xpath,Contains,CssSelector
最近有人问到定位问题,基本上我用以下三个方法可解决,但不同的项目使用方法不一样.以下为自己所用的简单记录说明 1.Xpath 经常使用且最能解决问题的定位 driver.findElement(By. ...
- css写复选框
前面讲过<完全使用css编写复选框>,后来在深入学习sass过程中,发现:这种写法虽然也能达到目的,但是稍嫌复杂了一点.这里介绍一种可以说更简单一点的方法,其实也就是html结构更简单一点 ...
- failed to open stream: Permission denied in警告错误
问题是文件所在目录的权限问题导致的.只需要将警告文件所在的目录权限更改为777(至少是006)即可 例如 (...a.log)failed to open stream: Permission den ...
- Python下的opencv小问题大智慧
1.今晚日了狗了,图像显示不按照预期出现,然后突然就好了...... 2.根据第一个问题举一个例子,另一个我没保存... 是不是分不清楚???? plt.imshow(wjy2, cmap='gr ...
- 20165205 2017-2018-2 《Java程序设计》第九周学习总结
20165205 2017-2018-2 <Java程序设计>第九周学习总结 教材学习内容总结 掌握URL类的使用方法 URL类的构造方法: public URL(String spec) ...
- TIDB资料收集
https://github.com/pingcap/docs-cn https://github.com/pingcap/docs-cn/blob/master/op-guide/binary-de ...
- 怎么分辨是eclipse还是 android studio开发的
eclipse开发的一般都会带.classpath文件.Android studio开发的一般都会有.gradle文件夹和build.gradle文件