jpa联表查询一对多

数据库

表company   

 id, name

表employee

employee_id,employee_name,company_id,price,monthtime,amount

实体类

Company

import lombok.Data;

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

/**
 * 测试一对多的查询   跟数据拼装差不多
 */
@Entity
@Table(name = "company")
@Data
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;
    //最重要的地方  1
    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "companyId")//指2表连接的关键字
    //or  2
    @oneToMany(mappedBy="companyId",cascade=CascadeType.All,fetch=FetchType.EAGER)
    private List employees=new ArrayList<>();



}

注解属性 mappedBy,是指关联关系可以从company类中的employees属性上获取;cascade属性设置成CascadeType.ALL,是说主从表全面建立级联关系;fetch属性设置成FetchType.EAGER,是指加载规则是即时加载。查看源码会发现默认情况下,OneToMany注解的fetch属性设置的是FetchType.LAZY。

 

Employee

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import javax.persistence.*;
import java.math.BigDecimal;

@Entity
@Table(name = "employee")
@Data
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int employeeId;

    private String employeeName;

    private int companyId;

    private BigDecimal price;

    private int monthtime;

    private BigDecimal amount;

}

Repository类

import com.xb.selltest.model.Company;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import javax.swing.text.html.Option;
import java.util.List;
import java.util.Optional;

public interface CompanyRepository extends JpaRepository {
       
            List  findById(int id);
}

后面的方法大家都该知道,写service,impl,controller.或者直接去test也行

 

 

     

你可能感兴趣的:(jpa联表查询一对多)