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属性. 搭建开发 ...
随机推荐
- Mysql数据类型DECIMAL(M,D)用法
在MySQL数据类型中,例如INT,FLOAT,DOUBLE,CHAR,DECIMAL等,它们都有各自的作用,下面我们就主要来介绍一下MySQL数据类型中的DECIMAL类型的作用和用法. 一般赋予浮 ...
- jquery选择器筛选器
jQuery对象 Query 对象就是通过jQuery包装DOM对象后产生的对象.jQuery 对象是 jQuery 独有的. 如果一个对象是 jQuery 对象, 那么它就可以使用 jQuery 里 ...
- Thinkphp3.2+PHPQRCode 二维码生成示例
下载phpqrcode 整合到Thinkphp框架 在“ThinkPHP\Library\Vendor\”下新建目录phpqrcode,将压缩包内容解压到该文件夹下. 下载地址:http://www. ...
- python r(不进行转义)的用法
第一种用法,直接针对字符串:r‘E:\ui\bbq.txt’ 第二种用法,针对变量名:r'' + 变量名
- linux进程端口防火墙
进程端口: 1.netstat –apn :查看所有的进程和端口使用情况 2.查看8080端口是否被占用 [root@localhost bin]# lsof -i:8080 3.查看防火墙开放的端口 ...
- 前端笔记二:DOM事件
---恢复内容开始--- ---恢复内容结束---
- 零基础学习python_生成器(49课)
一个生成器函数的定义很像一个普通的函数,除了当它要生成一个值的时候,使用yield关键字而不是return.如果一个def的主体包含yield,这个函数会自动变成一个生成器(即使它包含一个return ...
- QT编写TCP入门+简单的实际项目(附源程序)
我个人感觉学习QT不需要那么深入的了解,因为我就是编写一下界面来实现理想的功能而已,我不是靠这个吃饭,当然以后要是从事这个方向那就好好深入底层好好学了. 学习QT的TCP:第一步:去百度看看TCP的介 ...
- 寻找cost函数最小值:梯度下降与最小二乘法
Editted by MarkDown 寻找cost函数最小值:梯度下降与最小二乘法 参考:最小二乘法小结--刘建平 背景: 目标函数 = Σ(观测值-理论值)2 观测值就是我们的多组样本,理论值就是 ...
- 一个全栈Web/移动App开发学习路径
HTML.CSS 和 JavaScript 网页开发的基本元素,包括HTML.CSS个JavaScript.本课程完全适合零基础的同学,当然如果你有相关开发经验更好.在课程开始呢,我们先探索与讨论HT ...