One of the mybatis relational mappings is one of the many-to-many, one-to-one, and multiple-to-many.

Source: Internet
Author: User

One of the mybatis relational mappings is one of the many-to-many, one-to-one, and multiple-to-many.

I. Introduction:

This example describes how to use a customer and an order: a customer can have multiple orders, and an order only corresponds to one customer.


Ii. Example:

1. code structure:



2. Table creation statement:

CREATE DATABASE test;  USE test;CREATE TABLE person(  personId VARCHAR(36) PRIMARY KEY,  personName VARCHAR(64),  personAddress VARCHAR(128),  personTel VARCHAR(11));CREATE TABLE orders(  orderId VARCHAR(36) PRIMARY KEY,  orderNumber VARCHAR(20),  orderPrice INT,  pid VARCHAR(36));INSERT INTO person VALUES('001', 'Jack', 'Wuhan', '1234567');INSERT INTO orders VALUES('O_00001', '00001', 100, '001');INSERT INTO orders VALUES('O_00002', '00002', 200, '001');SELECT p.*, o.*FROM person p   JOIN orders o ON (p.personId=o.pid)WHERE p.personId = '001'

3. Customer entity:

/*** Customer entity */public class Person {private String id; private String name; private String address; private String tel; private List <Order> orders; @ Overridepublic String toString () {return "{id:" + id + ", name:" + name + ", address:" + address + ", tel: "+ tel + "}";}}

4. Order entity:

/*** Order entity */public class Order {private String id; private String number; private int price; private Person person Person; @ Overridepublic String toString () {return "{id: "+ id +", number: "+ number +", price: "+ price + "}";}}


5. One-to-Multiple object configuration: Person. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. zdp. domain. person "> <resultMap type =" Person "id =" personBean "> <id column =" personId "property =" id "/> <result column =" personName "property =" name "/> <result column =" personAddress "property =" address "/> <result column =" personTel "property =" tel "/> <! -- One-to-many relationship --> <! -- Property: the value of the Set property. ofType: indicates the type of elements in the collection --> <collection property = "orders" ofType = "Order"> <id column = "orderId" property = "id"/> <result column = "orderNumber" property = "number"/> <result column = "orderPrice" property = "price"/> </collection> </resultMap> <! -- Query Person by id and query Orders by Association --> <select id = "selectPersonById" parameterType = "string" resultMap = "personBean"> select p. *, o. * from person p, orders o where p. personId = o. pid and p. personId =#{ id} </select> </mapper>

6. Multiple-to-one instance Configuration:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. zdp. domain. order "> <resultMap type =" Order "id =" orderBean "> <id column =" orderId "property =" id "/> <result column =" orderNumber "property =" number "/> <result column =" orderPrice "property =" price "/> <! -- Multi-to-one relationship --> <! -- Property: indicates the property value. javaType: indicates the property type --> <association property = "person" javaType = "Person"> <id column = "personId" property = "id"/> <result column =" personName "property =" name "/> <result column =" personAddress "property =" address "/> <result column =" personTel "property =" tel "/> </association> </resultMap> <! -- Query Order by id and associate the query by Person --> <select id = "selectOrderById" parameterType = "string" resultMap = "orderBean"> select p. *, o. * from person p, orders o where p. personId = o. pid and o. orderId =#{ id} </select> </mapper>

7. Total configuration: sqlMapConfig. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <typeAliases> <typeAlias type =" com. zdp. domain. person "alias =" Person "/> <typeAlias type =" com. zdp. domain. order "alias =" Order "/> </typeAliases> <environments default =" development "> <environment id =" development "> <transactionManager type =" JDBC "/> <dataSource type = "POOLED"> <property n Ame = "driver" value = "com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // localhost/test "/> <property name =" username "value =" root "/> <property name =" password "value =" root "/> </dataSource> </environment> </environments> <mappers> <! -- Ing file location --> <mapper resource = "com/zdp/domain/Person. xml "/> <mapper resource =" com/zdp/domain/Order. xml "/> </mappers> </configuration>

8. Test file:

/*** Test one-to-many and multiple-to-one */public class MybatisTest {private SqlSessionFactory ssf; @ Beforepublic void initSF () throws Exception {String resource = "sqlMapConfig. xml "; InputStream inputStream = Resources. getResourceAsStream (resource); ssf = new SqlSessionFactoryBuilder (). build (inputStream) ;}@ Test // One-to-multiple association query public void selectPersonById () throws Exception {SqlSession session = ssf. openSession (); Person person = session. selectOne ("com. zdp. domain. person. selectPersonById "," 001 "); System. out. println (person. getOrders () ;}@ Test // public void selectOrderById () throws Exception {SqlSession session = ssf. openSession (); Order order = session. selectOne ("com. zdp. domain. order. selectOrderById "," O_00001 "); System. out. println (order. getPerson (). getName ());}}



Mybatis relational ing in Java, for example: one-to-many

There is no difference between using list and set. In most cases, set is used.
 
Hibernate annotations map the relationship between one-to-many and three tables. The existing three tables A, B, c a and B are one-to-many, and B and C are many-to-many.

Write a temporary Method
Public class {
Private Set <B> B;
Private Set <C> c; // here I want to use A to directly retrieve the Set of C. How should I write the link?
@ Transient
Public Set <C> getC (){
Set <C> cs = new HashSet <C> ();
If (B! = Null ){
For (B o: B ){
Cs. add (B. getC ());
}
}
Return cs;
}
}

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.