spring data jpa many queries

In many relationship, we used to call it a party to the main table, the multi-party call from the table. To-many relationship in the database, you need to use a foreign key constraint database.

What is a foreign key?

Refers to a column from the table, referring to the primary key value of the primary table, the column is a foreign key.

 

package com.ytkj.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 *          @Entity
 * Function: Specifies the current class is the entity class.
 *         @Table
 * Function: Specifies the correspondence between the entity classes and tables.
 * Attributes:
 * Name: Specifies the name of the database table
 *         @Id
 * Function: Specifies the current field is the primary key.
 *         @GeneratedValue
 * Function: generating a primary key specified manner. .
 * Attributes:
 * Strategy: Specifies the primary key generation strategy.
 *         @Column
 * Function: a correspondence relationship between the entities specified class attribute database table and
 * Attributes:
 * Name: Specifies the name of the database table column.
 * Unique: whether the only
 * Nullable: Can be empty
 * Inserttable: Can insert
 * Updateable: Can update
 * ColumnDefinition: DDL to create this column when defining the build table
 * SecondaryTable: from the table name. If this column is not built on the main table (the default built in the main table), the defining attributes of the column where the table name built from the development environment [focus]
 * @OneToMany:
 * Function: to build relationships-many mapping
 * Attributes:
 * TargetEntityClass: Specifies the number of multi-class bytecode
 * MappedBy: Specifies the name of the referenced object from the main table entity class table.
 * Cascade: cascading actions specified to be used
 * Fetch: Specifies whether to employ lazy loading
 * OrphanRemoval: whether to use an orphan delete
 *
 *          @ManyToOne
 * Role: many-establish relations
 * Attributes:
 * TargetEntityClass: one of a specified entity class bytecode
 * Cascade: cascading actions specified to be used
 * Fetch: Specifies whether to employ lazy loading
 * Optional: association is optional. If set to false, it must always exist non-empty relationship.
 *
 *          @JoinColumn
 * Function: to define the relation of the primary key and foreign key fields fields.
 * Attributes:
 * Name: Specifies the name of the foreign key field
 * ReferencedColumnName: Specifies a reference to the main table's primary key field name
 * Unique: is unique. The default value is not unique
 * Nullable: whether to allow empty. The default value allows.
 * Insertable: whether to allow insertion. The default value allows.
 * Updatable: whether to allow updates. The default value allows.
 * ColumnDefinition: definition information column.
 *
 * Cascade: cascade configuration operation
 * CascadeType.MERGE cascading update
 * CascadeType.PERSIST cascade saves:
 * CascadeType.REFRESH cascade refresh:
 * CascadeType.REMOVE cascade delete:
 * CascadeType.ALL contains all
 *
 * Customer entity class
 * Establish the mapping
 * Entity classes and table mapping
 * Entity class and attribute mapping table field
 */
@Entity
@Table(name = "cst_customer")
public class Customer implements Serializable {
    /**
     * Declare a primary key configuration
     */
    @Id
    /**
     * Configuration of the primary key generation strategy
     */
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    /**
     * Correspondence relationship between the entities specified class attribute database table and
     */
    @Column(name ="cust_id")
    private Long custId; // customer master key
    @Column(name = "cust_name")
    private String custName; // Customer Name
    @Column(name ="cust_source" )
    private String custSource; // client base
    @Column(name = "cust_industry")
    private String custIndustry; // customer industries
    @Column(name ="cust_level")
    private String custLevel; // customer level
    @Column(name ="cust_address")
    private String custAddress; // customer address
    @Column(name = "cust_phone")
    private String custPhone; // customer calls

    // Configure customer relationships and contacts (a customer has multiple contacts, to-many)
    /**
     * Use annotations in the form of multi-table configuration relationship
     * 1. Statement relations
     * @OneToMany: Configure-to-many
     * TargetEntity: bytecode object other objects
     * 2. Use a foreign key
     *           @JoinColumn
     * Name: the name of the foreign key field
     * ReferencedColumnName: primary key field name reference in the primary table
     * On the customer master table entity class (a second party) Added foreign key configuration, so for customers, but also includes the maintenance of the foreign key
     *
     * Cascade: cascade configuration operation
     * CascadeType.MERGE cascading update
     * CascadeType.PERSIST cascade saves:
     * CascadeType.REFRESH cascade refresh:
     * CascadeType.REMOVE cascade delete:
     * CascadeType.ALL contains all
     */
    @OneToMany(targetEntity =LinkMan.class,cascade = CascadeType.ALL)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
    private List<LinkMan> linkMans=new ArrayList<>();




    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public List<LinkMan> getLinkMans() {
        return linkMans;
    }

    public void setLinkMans(List<LinkMan> linkMans) {
        this.linkMans = linkMans;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custAddress='" + custAddress + '\'' +
                ", custPhone='" + custPhone + '\'' +
                '}';
    }
}

 

  

package com.ytkj.entity;

import javax.persistence.*;
import java.io.Serializable;


/**
 * Contact entity class
 */
@Entity
@Table(name = "cst_linkman")
public class LinkMan implements Serializable {

    /**
     * Primary Key
     */
    @Id
	@GeneratedValue(strategy= GenerationType.IDENTITY)
	@Column(name="lkm_id")
	private Long lkmId;
	@Column(name="lkm_name")
	private String lkmName;
	@Column(name="lkm_gender")
	private String lkmGender;
	@Column(name="lkm_phone")
	private String lkmPhone;
	@Column(name="lkm_mobile")
	private String lkmMobile;
	@Column(name="lkm_email")
	private String lkmEmail;
	@Column(name="lkm_position")
	private String lkmPosition;
	@Column(name="lkm_memo")
	private String lkmMemo;

    /**
     * Configure relationship to the customer's many-to-contact
     * 1 configuration table relationship
     *       @ManyToOne
     * Configure many-relationship
     * TargetEntity: other entity class bytecode
     * Configuration foreign key
     * Name: the name of the foreign key field
     * ReferencedColumnName: primary key field name reference in the primary table
     * @return
     */
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
	private Customer customer;


    public Long getLkmId() {
        return lkmId;
    }

    public void setLkmId(Long lkmId) {
        this.lkmId = lkmId;
    }

    public String getLkmName() {
        return lkmName;
    }

    public void setLkmName(String lkmName) {
        this.lkmName = lkmName;
    }

    public String getLkmGender() {
        return lkmGender;
    }

    public void setLkmGender(String lkmGender) {
        this.lkmGender = lkmGender;
    }

    public String getLkmPhone() {
        return lkmPhone;
    }

    public void setLkmPhone(String lkmPhone) {
        this.lkmPhone = lkmPhone;
    }

    public String getLkmMobile() {
        return lkmMobile;
    }

    public void setLkmMobile(String lkmMobile) {
        this.lkmMobile = lkmMobile;
    }

    public String getLkmEmail() {
        return lkmEmail;
    }

    public void setLkmEmail(String lkmEmail) {
        this.lkmEmail = lkmEmail;
    }

    public String getLkmPosition() {
        return lkmPosition;
    }

    public void setLkmPosition(String lkmPosition) {
        this.lkmPosition = lkmPosition;
    }

    public String getLkmMemo() {
        return lkmMemo;
    }

    public void setLkmMemo(String lkmMemo) {
        this.lkmMemo = lkmMemo;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    @Override
    public String toString() {
        return "LinkMan{" +
                "lkmId=" + lkmId +
                ", lkmName='" + lkmName + '\'' +
                ", lkmGender='" + lkmGender + '\'' +
                ", lkmPhone='" + lkmPhone + '\'' +
                ", lkmMobile='" + lkmMobile + '\'' +
                ", lkmEmail='" + lkmEmail + '\'' +
                ", lkmPosition='" + lkmPosition + '\'' +
                ", lkmMemo='" + lkmMemo + '\'' +
                '}';
    }



}

  

package com.ytkj.dao;

import com.ytkj.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

/**
 * JpaRepository <entity class type, primary key type>: to perform basic CRUD operations
 * JpaSpecificationExecutor <Entity class types>: for complex queries (pagination query)
 */
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {


}

  

package com.ytkj.dao;

import com.ytkj.entity.LinkMan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface LinkManDao extends JpaRepository<LinkMan,Integer>, JpaSpecificationExecutor<LinkMan> {

}

  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/data/jpa
		http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <-! Spring and spring-data-jpa integration ->

    <-! 1. Create an object to spring entityManagerFactory Management ->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <-! Database injected ->
        <property name="dataSource" ref="dataSource"/>
        <! - Scan configuration package ->
        <property name="packagesToScan" value="com.ytkj.entity"/>
        <-! Jpa achieve factory ->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
        </property>
        <-! JPA suppliers adapter ->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <! - Configure whether to automatically create database tables ->
                <property name="generateDdl" value="false" />
                <! - Specify the database type ->
                <property name="database" value="MYSQL" />
                <- Database dialect:! Supports unique grammar ->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <! - whether sql statement ->
                <property name="showSql" value="true" />
            </bean>
        </property>

        <- jpa dialect:! Advanced Features ->
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
    </bean>

    <-! 2 Create Data Connection Pool ->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <-! Database information ->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://192.168.2.101:3306/ytkj?serverTimeZone=UTC"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <-!. 3 integrated spring-data-jpa ->
    <jpa:repositories base-package="com.ytkj.dao" transaction-manager-ref="transacManager" entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>

    <-! 4 Configure Transaction Manager ->
    <bean id="transacManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <! -. 5 Declarative transaction ->
    <tx:advice id="txAdvice" transaction-manager="transacManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 5.aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.ytkj.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>

    <context:component-scan base-package="com.ytkj"/>

</beans>

  

import com.ytkj.dao.CustomerDao;
import com.ytkj.dao.LinkManDao;
import com.ytkj.entity.Customer;
import com.ytkj.entity.LinkMan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

/**
 * Test-many save / delete operations
 */
@RunWith (SpringJUnit4ClassRunner.class) unit test environment // Declare spring provided
@ContextConfiguration (locations = "classpath: applicationContext.xml") // spring configuration of the specified container
public class SpringdatajpaOneToManyTest {
    @Autowired
    CustomerDao customerDao;
    @Autowired
    LinkManDao linkManDao;

    /**
     * Save operation
     * Requirements:
     * Save a client and a contact
     * Claim:
     * Create a client object and a Contact object
     * Establish relationships (two-way-to-many relationship) between the client and contacts
     * Customer first save and then save the contact
     * Question:
     * When we establish a two-way relationship, save the main table, and then save from the table:
     * 2 will produce an insert and update.
     * The actual development, we only need two insert.
     *
     */
    @Test
    @ Transactional // add transaction
    @Rollback (value = false) // not set automatic rollback
    public  void  test(){
        // Create Customer Contact
        Customer customer=new Customer();
        customer.setCustName("丁丁");

        LinkMan linkMan=new LinkMan();
        linkMan.setLkmName ( "Fang Fang");
        /**
         * Configure the client to contact relationships (one to many)
         */
        customer.getLinkMans().add(linkMan);
        customerDao.save(customer);
        linkManDao.save(linkMan);
    }


    @Test
    @ Transactional // add transaction
    @Rollback (value = false) // not set automatic rollback
    public  void  test2(){
        // Create Customer Contact
        Customer customer=new Customer();
        customer.setCustName("丁丁1");

        LinkMan linkMan=new LinkMan();
        linkMan.setLkmName ( "fangfang 1");
        /**
         * Configure a contact to the customer relationship (many to one)
         */
        linkMan.setCustomer(customer);
        customerDao.save(customer);
        linkManDao.save(linkMan);
    }


    @Test
    @ Transactional // add transaction
    @Rollback (value = false) // not set automatic rollback
    public  void  test3(){
        // Create Customer Contact
        Customer customer=new Customer();
        customer.setCustName("丁丁3");

        LinkMan linkMan=new LinkMan();
        linkMan.setLkmName ( "fangfang 3");

        /**
         * Configure the client to contact relationships (one to many)
         */
        customer.getLinkMans().add(linkMan);
        /**
         * Configure a contact to the customer relationship (many to one)
         */
        linkMan.setCustomer(customer);
        customerDao.save(customer);
        linkManDao.save(linkMan);
    }


    /**
     * Add cascading
     * Need to add cascade property on operating entity class theme
     */
    @Test
    @ Transactional // add transaction
    @Rollback (value = false) // not set automatic rollback
    public  void  test4(){
        // Create Customer Contact
        Customer customer=new Customer();
        customer.setCustName("丁丁4");

        LinkMan linkMan=new LinkMan();
        linkMan.setLkmName ( "fangfang 4");

        /**
         * Configure the client to contact relationships (one to many)
         */
        customer.getLinkMans().add(linkMan);
        /**
         * Configure a contact to the customer relationship (many to one)
         */
        linkMan.setCustomer(customer);
        customerDao.save(customer);

    }

    /**
     * Cascading Delete
     * Need to add cascade property on operating entity class theme
     */
    @Test
    @ Transactional // add transaction
    @Rollback (value = false) // not set automatic rollback
    public  void  test5(){
       // Query No. 1 customer
        Customer customer = customerDao.findOne(1l);
        // delete Customer 1
        customerDao.delete(customer);

    }

}

  

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ytkj</groupId>
    <artifactId>springdatajpa</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <spring.version>5.1.7.RELEASE</spring.version>
        <hibernate.version>5.0.7.Final</hibernate.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>5.1.6</mysql.version>
    </properties>
    <dependencies>



        <-! Junit unit test ->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>

        <!-- spring beg -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <-! Spring orm framework of support ->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring end -->

        <!-- hibernate beg -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <!-- hibernate end -->

        <!-- c3p0 beg -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- c3p0 end -->

        <!-- log end -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <-! Sprngdatajpa dependent ->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <-! El beg to be introduced using the spring data jpa ->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>

        <!-- el end -->
    </dependencies>

</project>

  

 

Guess you like

Origin www.cnblogs.com/yscec/p/12008156.html