Ing and querying multiple-to-multiple relationships in MyBatis and multiple-to-one in mybatis

Source: Internet
Author: User

Ing and querying multiple-to-multiple relationships in MyBatis and multiple-to-one in mybatis

First, let's talk about the requirements:

All books in the database are displayed on the page, and the category of the book is displayed at the same time (a book may belong to multiple categories at the same time)

 

Test environment: MySQL and MyEclipse

Create a table:

The author uses an intermediate table to connect the book table and the book category table. The book table does not use a foreign key to associate the book category table.

Instead, the primary key and category primary key of the book are referenced in the intermediate table.

Use an intermediate table to indicate the relationship between a book and its category

 

Create a book table (book number, book name)

create table book(    bid int primary key auto_increment,    bname varchar(20)                                     );

Create a Category Table (Category Number and category name)

create table category(    cid int primary key auto_increment,    cname varchar(20));

Create an intermediate table (Book Number, category number)

create table middle(    m_bid int,    m_cid int,    constraint fk_bid foreign key(m_bid) references book(bid),    constraint fk_cid foreign key(m_cid) references category(cid));

Insert Test Data

Insert into category values (default, 'java'); insert into category values (default, 'c ++ '); insert into category values (default, 'mysql '); insert into book values (default, 'SQL technology'); insert into book values (default, 'ssm + MySQL details'); insert into book values (default, 'C ++ compared with java '); insert into middle values ); insert into middle values (3, 2); insert into middle values (3, 1 );

In the inserted data, the first book has a category, and the second and third books both have two categories.

So far, the database is finished. Below, the entity class, DAO interface, and XML ing file generated through MyBatis-Generator will not be clicked here

For convenience, I will use the Java project demonstration here to put the automatically generated file into the newly created Java project, import the relevant Jar package, the project structure is as follows:

Now let's take a look at the generated library entity class.

public class Book {
private Integer bid; private String bname; public Integer getBid() { return bid; } public void setBid(Integer bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname == null ? null : bname.trim(); }}

There are only two attributes: The book number and the book name. Our requirement is to obtain all the categories of the book at the same time, therefore, we can consider adding a collection of library classes to the library entity class.

The modified library entity class is as follows:

public class Book {    private Integer bid;    private String bname;    private List<Category> categories;    public Integer getBid() {        return bid;    }    public void setBid(Integer bid) {        this.bid = bid;    }    public String getBname() {        return bname;    }    public void setBname(String bname) {        this.bname = bname == null ? null : bname.trim();    }    public List<Category> getCategories() {        return categories;    }    public void setCategories(List<Category> categories) {        this.categories = categories;    }}

Next, we will start to write SQL statements and use connection queries to find out all books and book categories.

select     * from     book b  inner join        middle m  on      b.bid=m.m_bid  inner join      category c  on      m.m_cid=c.cid

The execution result is as follows, which perfectly shows all books and their categories.

Next we will move our hands and feet in the XML ing file so that the data can be automatically filled into the library entity class as we expected.

The ing file and DAO interface of the book are cleared as follows:

<?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="com.mybatis.dao.BookMapper" >    <select id="queryAll">            </select></mapper>
public interface BookMapper {       List<Book> queryAll();   }

 

After clearing the image, we can write it as follows:

<?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="com.mybatis.dao.BookMapper" >        <resultMap type="com.mybatis.entity.Book" id="bookMap">        <id property="bid" column="bid" />        <result property="bname" column="bname" />                <collection  property="categories"  ofType="com.mybatis.entity.Category">            <id property="cid" column="cid" />            <result property="cname" column="cname" />            </collection>    </resultMap>    <select id="queryAll" resultMap="bookMap">        select             *         from             book b        inner join              middle m        on            b.bid=m.m_bid        inner join            category c        on            m.m_cid=c.cid    </select></mapper>

Finally, we compile the main method for testing.

public class MyMain {        public static void main(String[] args) throws IOException {                 String resource = "mybatis-config.xml";         Reader reader = Resources.getResourceAsReader(resource);         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);         SqlSession session = factory.openSession();                  BookMapper bookMapper = session.getMapper(BookMapper.class);         for (Book book : bookMapper.queryAll()) {            System.out.print("["+book.getBname()+"]");            for(Category category :book.getCategories()){                System.out.print(category.getCname()+"\t");            }            System.out.println("\n");        }    }}

The test result is as follows:

Successfully output all books and corresponding book categories

Download the complete project: Click to download (for convenience, I introduced the SSM integrated jar package into the project, you can delete useless jar packages)

I have limited capabilities. What can I do or are you welcome to raise!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.