Mybatis注解方式实现一对一,一对多的关联查询

Step1 创建数据库表

使用Mysql WorkBench创建数据库表ssm20191229test,并创建table:user,book,addrss,如下:
Mybatis注解方式实现一对一,一对多的关联查询_第1张图片
Mybatis注解方式实现一对一,一对多的关联查询_第2张图片
Mybatis注解方式实现一对一,一对多的关联查询_第3张图片
Mybatis注解方式实现一对一,一对多的关联查询_第4张图片
Mybatis注解方式实现一对一,一对多的关联查询_第5张图片
Mybatis注解方式实现一对一,一对多的关联查询_第6张图片

Step2 创建maven工程

创建maven工程:mybatis20190103oneToOne,完整的结构目录如下:
Mybatis注解方式实现一对一,一对多的关联查询_第7张图片

Step3 配置pom.xml和mybatis.xml

pom.xml代码如下:


  4.0.0
  com.mybatis
  mybatis20190102oneToOne
  0.0.1-SNAPSHOT
  
  
    
         
               org.apache.maven.plugins
               maven-compiler-plugin 
               3.8.0             
         	   
         	                   
                 10     
                 10   
    		         
          
      
  
  
  
  
  	
  		com.mybatis
 		pomModule
 		0.0.1-SNAPSHOT
  	
  

mybatis.xml配置如下:




	
		
			
			
				
				
				
				
			
		
	

	
		
		
		
		
		
		
		
	


Step4 创建pojo类

User.java

package com.cr.pojo;

import java.util.List;

public class User {
	private int userId;
	private String userName;
	private String userPassword;
	private int userAge;
	private String userEmail;
	private Address userAddress;
	private List books;
	
	public List getBooks() {
		return books;
	}

	public void setBooks(List books) {
		this.books = books;
	}

	public Address getAddress() {
		return userAddress;
	}

	public void setAddress(Address address) {
		this.userAddress = address;
	}

	public int getUserAge() {
		return userAge;
	}

	public void setUserAge(int userAge) {
		this.userAge = userAge;
	}

	public String getUserEmail() {
		return userEmail;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPassword() {
		return userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
}

Address.java

package com.cr.pojo;

/**  
* 

Title: Address.java

*

Description:

*

Copyright: Copyright (c) 2019

*

Company:uestc

* @author ChenRan * @date 2019年1月2日 * @version 1.0 */ public class Address { private int addressId; private String province; private String city; public int getAddressId() { return addressId; } public void setAddressId(int addressId) { this.addressId = addressId; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String toString() { return this.province+this.city; } }

Book.java

package com.cr.pojo;

public class Book 
{
	private int bookId;
	private String bookName;
	private int totalPage;
	private int price;

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getPrice() {
		return price;
	}
	
	public void setPrice(int price) {
		this.price = price;
	}
}

Step5 创建mapper类

UserMapper.java

package com.cr.mapper;

import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import com.cr.pojo.User;

public interface UserMapper
{
	
	//one to one 
	@Select("select * from user where userId = #{userId}")
	@Results({
		@Result(id=true,column="userId",property="userId"),
		@Result(column="userName",property="userName"),
		@Result(column="userPassword",property="userPassword"),
		@Result(column="userAge",property="userAge"),
		@Result(column="userEmail",property="userEmail"),
		@Result(column="userId",property="userAddress",one=@One(select="com.cr.mapper.AddressMapper.getAddressByUserId",fetchType= FetchType.EAGER))
})
	public User getUserById(int userId);
	
	//one to many
	@Select("select * from user where userId=#{userId}")
	@Results({
		@Result(id=true,column="userId",property="userId"),
		@Result(column="userName",property="userName"),
		@Result(column="userPassword",property="userPassword"),
		@Result(column="userAge",property="userAge"),
		@Result(column="userEmail",property="userEmail"),
		@Result(column="userId",property="books",many=@Many(select="com.cr.mapper.BookMapper.getBooksByUserId",fetchType= FetchType.EAGER))
	})
	public User getUserAndBooksById(int userId);
}

AddressMapper.java

package com.cr.mapper;

import org.apache.ibatis.annotations.Select;

import com.cr.pojo.Address;
public interface AddressMapper 
{
	@Select("select * from address where userId=#{userId}")
	public Address getAddressByUserId(int userId);
}

BookMapper.java

package com.cr.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.cr.pojo.Book;
public interface BookMapper 
{	
	@Select("select * from book where userId = #{userId}")
	public List getBooksByUserId(int userId);
}

Step6 创建测试类

oneToOne.java

package com.cr.test;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.cr.mapper.UserMapper;
import com.cr.pojo.User;

public class OneToOne 
{
	 private static SqlSessionFactory sqlSessionFactory;
	    private static Reader reader;
	    

	    static {
	        try {
	            reader = Resources.getResourceAsReader("mybatis.xml");
	            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

	    public static SqlSessionFactory getSession() {
	        return sqlSessionFactory;
	    }

	    public static void main(String[] args) 
	    {
	    	test(4);
	    }
	    
	    //测试模块
	    private static void test(int userId) 
	    {	
	    	 SqlSession session = sqlSessionFactory.openSession();
		        try 
		        {
		        	UserMapper userMapper = session.getMapper(UserMapper.class);
		        	User user = userMapper.getUserById(userId);
		        	if(user != null)
		        	{
		        		printUser(user);
		        	}
		        	else
		        	{
		        		System.out.println("userId为"+userId+"的用户不存在!可能未创建或者已经被删除。");
		        	}

		        } 
		        finally 
		        {
		            session.close();
		        }
	    }
	    //输出用户信息
	    private static void printUser(User user)
	    {
	    	System.out.println("用户id:"+user.getUserId()+"\n姓名:"
		        	+user.getUserName()+"\n年龄:"+user.getUserAge()
		        	+"\n邮箱:"+user.getUserEmail()+"\n地址:"+user.getAddress().toString());
	    }
	    
}

oneToMany.java

package com.cr.test;

import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.cr.mapper.UserMapper;
import com.cr.pojo.Book;
import com.cr.pojo.User;

/**  
* 

Title: oneToMany.java

*

Description:

*

Copyright: Copyright (c) 2019

*

Company:uestc

* @author ChenRan * @date 2019年1月2日 * @version 1.0 */ public class oneToMany { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } public static SqlSessionFactory getSession() { return sqlSessionFactory; } /** * @param args */ public static void main(String[] args) { test(5); } private static void test(int userId) { SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.getUserAndBooksById(userId); if(user != null) { printUserAndBooks(user); } else { System.out.println("userId为"+userId+"的用户不存在!可能未创建或者已经被删除。"); } } finally { session.close(); } } private static void printUserAndBooks(User user) { System.out.println("用户id:"+user.getUserId()+"\n姓名:" +user.getUserName()+"\n年龄:"+user.getUserAge() +"\n邮箱:"+user.getUserEmail()); List books = user.getBooks(); String messsage = "喜欢的书籍:"; for(Book book:books) { messsage = messsage+book.getBookName()+" "; } System.out.println(messsage); } }

结语

测试结果如下:
运行oneToOne.java:
Mybatis注解方式实现一对一,一对多的关联查询_第8张图片
运行oneToMany.java:
Mybatis注解方式实现一对一,一对多的关联查询_第9张图片
时间关系,写的比较简略。(2019.01.03)

你可能感兴趣的:(mybatis,maven,mybatis,一对多,一对一,注解)