如何使用 JPA 和休眠连接非主键上的表
2022-09-01 12:14:32
我有 3 个模型 , , .我需要通过地图访问用户的房子。唯一的问题是这是一个旧的数据库,我无法改变我需要映射到 using 的事实,这是一个非主键。User
House
UserHouseMap
User
UserHouseMap
user.name
休眠不断给我错误,说我需要把它作为主键,否则我得到错误说A JPA error occurred (Unable to build EntityManagerFactory): Unable to find column with logical name: name in org.hibernate.mapping.Table(users) and its related supertables and secondary tables
我尝试过作为解决方法,但这不起作用。我也试过了,但也没有用。这是我的解决方案@Formula
@JoinColumnOrFormula
@Formula
@Expose
@ManyToOne(targetEntity = House.class)
@Formula("(select * from houses inner join user_house_map on houses.house_name = user_house_map.house_name where user_house_map.user_name=name)")
public House house;
这是我对解决方案的尝试。@JoinColumnOrFormula
@Expose
@ManyToOne(targetEntity = House.class)
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(formula=@JoinFormula(value="select name from users where users.id= id", referencedColumnName="name")),
@JoinColumnOrFormula(column = @JoinColumn(name= "house_name", referencedColumnName="house_name"))
})
public House house;
这是我的映射
@Id
@GeneratedValue
@Expose
public Long id;
@Expose
@Required
@ManyToOne
@JoinTable(
name="user_house_map",
joinColumns=
@JoinColumn(unique=true,name="user_name", referencedColumnName="name"),
inverseJoinColumns=
@JoinColumn(name="house_name", referencedColumnName="house_name"))
private House house;
以下是数据库架构
用户
Table "public.users"
Column | Type | Modifiers
-----------------------+-----------------------------+-----------------------------
name | character varying(255) |
id | integer | not null
Indexes:
"user_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"housing_fkey" FOREIGN KEY (name) REFERENCES user_house_map(user_name) DEFERRABLE INITIALLY DEFERRED
房子
Table "public.houses"
Column | Type | Modifiers
---------------+------------------------+-----------
house_name | character varying(255) | not null
address | text |
city | text |
state | text |
zip | integer |
zip_ext | integer |
phone | text |
Indexes:
"house_pkey" PRIMARY KEY, btree (house_name)
Referenced by:
TABLE "user_house_map" CONSTRAINT "house_map_fkey" FOREIGN KEY (house_name) REFERENCES house(house_name) DEFERRABLE INITIALLY DEFERRED
用户之家地图
Table "public.user_house_map"
Column | Type | Modifiers
-------------+------------------------+-----------
user_name | character varying(255) | not null
house_name | character varying(255) | not null
Indexes:
"user_house_map_pkey" PRIMARY KEY, btree (user_name)
"user_house_map_house_key" btree (house_name)
Foreign-key constraints:
"user_house_map_house_fkey" FOREIGN KEY (house_name) REFERENCES houses(house_name) DEFERRABLE INITIALLY DEFERRED
Referenced by:
TABLE "users" CONSTRAINT "housing_fkey" FOREIGN KEY (name) REFERENCES user_house_map(user_name) DEFERRABLE INITIALLY DEFERRED