我的表客户有参数:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
public Long id_crm;
public String City;
public String Country;
和第二个表格,我存储了一些联系信息。
@Entity
public class CustomerContact {
@Id
public Long id;
public Role role;
public Department department;
public Long customer_id_crm
}
第二个表是从外部crm app获得的,因此我已将关系列id_crm
添加为外键。
我想在列上的这两个实体之间建立关系:
Customer.id_crm
和CustomerContact.customer_id_crm
对它的sql查询将如下所示:
Select * FROM Customer
Join CustomerContact
on Customer.id_crm=CustomerContact.customer_id_crm
我甚至可以用jpa实现这个目标吗?如果是这样?怎么做?
答案 0 :(得分:0)
试试这个
session.createQuery("select c, cc from Customer c, CustomerContact cc where c.id_crm = cc.customer_id_crm")
答案 1 :(得分:0)
这是与canvas有一对多关系的person类:
@Entity
@Table(name="person")
public class Person implements UserDetails{
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
@SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
private int id;
@OneToMany(mappedBy = "person1",fetch = FetchType.EAGER,cascade = CascadeType.REMOVE)
private Set<Canvas> canvas1 = new HashSet<Canvas>();
public Set<Canvas> getCanvas1() {
return canvas1;
}
public void setCanvas1(Set<Canvas> canvas1) {
this.canvas1 = canvas1;
}
}
画布模型:
@Entity
@Table(name = "canvas")
public class Canvas {
@Id
@Column(name="canvasid")
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "canvas_gen")
@SequenceGenerator(name = "canvas_gen",sequenceName = "canvas_seq")
private int canvasid;
@ManyToOne
@JoinColumn(name = "id",nullable = false)
@JsonIgnore
private Person person1;
public Person getPerson1() {
return person1;
}
public void setPerson1(Person person1) {
this.person1 = person1;
}
public int getPerson1id(){
return this.person1.getId();
}
}
当你想要添加画布时,这是DAOImpl:
public void addCanvas(Canvas canvas, Person person) {
int id = person.getId();
if( session == null) {
session = this.sessionFactory.openSession();
}else {
session = this.sessionFactory.getCurrentSession();
}
Person person1 = (Person) session.get(Person.class,id);
person.getCanvas1().add(canvas);
canvas.setPerson1(person1);
session.merge(canvas);
session.flush();
}
我也有类似于你的查询的方法:
public List<Canvas> listCanvasPerson(Person person) {
int id = person.getId();
if(session == null){
session = this.sessionFactory.openSession();
} else{
session = this.sessionFactory.getCurrentSession();
}
Query query = session.createQuery("from Canvas as c where c.person1.id=:id order by c.canvasnumber");
query.setParameter("id",id);
List<Canvas> canvasList = query.list();
希望这会有所帮助,如果我在某个地方犯了错误,请告诉我。请理解我使用的是简单的密钥,而不是复合密钥。