Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

hibernate - JPA : How to manage unmapped Table using Criteria API

I have @ManyToMany relationship between two entities A and B, so Hibernate creates for me an unmapped table named A_B into the database which I don't have a related entity in my java code. Also, I'm trying to query that A_B table from my dao using Criteria API. Could someone help me please to figure out a solution? I'm trying to do something like this example in Criteria API:

select * from A_B where A_B.column = id_input;

question from:https://stackoverflow.com/questions/65844068/jpa-how-to-manage-unmapped-table-using-criteria-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First is mapping ORM. In JPA (using JPQL) you use fields of classes, so if you have relation in class, you can use it to create method name in repository. Example:

client entity:

@Entity
public class Client {

@Id
@GeneratedValue
private Long id;
private String name;
private String description;

}

and product entity with mark that relation is mapping from client enitity

@Entity
public class Product {

@Id
@GeneratedValue
private Long id;
@Column(name="name")
private String productName;
private String description;

@ManyToMany(mappedBy="products")
private List<Client> clients;

}

Now repository to find clients by product name:

@Repository
public interface ClientRepository extends JpaRepository<Client, Long>{

List<Client> findByProducts_ProductName(String name);

}

Above example create join table with name client_products and columns clients_id and products_id - used field names to generate column names. If you want to custom table name or column names, you have to map this on client entity:

@ManyToMany
@JoinTable(
        name="products_of_client",
        joinColumns = @JoinColumn(name="client_id"),
        inverseJoinColumns = @JoinColumn(name="product_id")
        )
private List<Product> products;

this change create table with name products_of_client and column names client_id and product_id. It does not affect on method name in repository


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...