我是hibernate的新手,我遇到了有关映射类的问题。 我有两个类Song和User
public class Song implements Serializable {
private Album album;
private String title;
private int rating;
private String artist;
private String composer;
private Genre genre;
private int songId;
//getters and setters
}
public class user{
private String userName;
private String password;
private int user_id;
//getters and setters
}
我必须使用他帐户中的歌曲映射每个用户。要做到这一点,我有一个表user_songs_mapping表,其中有song_id和user_id作为列...我没有得到如何映射这种关系我休眠
答案 0 :(得分:0)
您应该使用多对多设置,例如注释你是< d:
class Song {
@ManyToMany
@JoinTable( name = "user_songs_mapping",
joinColumns = @JoinColumn ( name = "song_id", referencedColumnName = "songid" ), //assuming the id column in the song table is named songid
inverseJoinColumns = @JoinColumn ( name = " user_id", referencedColumnName = "userid" ) ) //assuming the id column in the user table is named userid
Set<Users> users;
}
class User {
@ManyToMany( mappedBy = "users" )
Set<Song> songs;
}
请注意,一方定义表,另一方只声明在哪里找到映射。在我的示例中,Song
将是拥有方,即您需要更新Song
中设置的用户以保持更改。如果您希望User
成为拥有者,只需切换注释并加入列。
更新:重读您的问题我假设您想要一个单向关联用户 - >歌曲。因此,只需将关系添加到User
:
class User{
@ManyToMany
@JoinTable( name = "user_songs_mapping",
joinColumns = @JoinColumn ( name = " user_id", referencedColumnName = "userid" ),
inverseJoinColumns = @JoinColumn ( name = "song_id", referencedColumnName = "songid" ) )
Set<Song> songs;
}
答案 1 :(得分:0)
如果您使用xml将表映射到类,那么它将是这样的:
<hibernate-mapping>
<class name="User" table="user">
<!-- column attribute contains the name using in data base and name attribute contains the name using in calss -->
<id name="id" type="int" column="user_id">
<generator class="native"/>
</id>
<set name="songs" cascade="save-update" table="user_songs_mapping">
<key column="user_id"/>
<many-to-many column="song_id" class="Song"/>
</set>
<property name="userName" column="user_name" type="string"/>
<!-- other properties-->
</class>
<class name="Song" table="song">
<id name="songId" type="int" column="song_id">
<generator class="native"/>
</id>
<property name="title" column="title" type="string"/>
<!-- other properties-->
</class>
</hibernate-mapping>
&#13;
答案 2 :(得分:0)
它是一个与连接表有多对多关系的经典案例。
两个类声明都应该在具有其他类对象的集合上具有@manyToMany注释。 通过使用连接注释“here User”使一个类成为连接所有者,并将layoutby属性放在其他类“here Song”中。 示例如下。
public class User{
@Id
@Column(name="USER_ID")
private int user_id;
@Column(name="USER_NAME")
private String userName;
@ManyToMany(cascade = {Google this and use what you want as per your requarement})
@JoinTable(name="USER_SONGS_MAPPING",
joinColumns={@JoinColumn(name="USER_ID")},
inverseJoinColumns={@JoinColumn(name="SONG_ID")})
private Set<Song> songs= new HashSet<Song>();
//getters and setters
}
public class Song {
// Other fileds
@ManyToMany(mappedBy="songs")
private Set<User> users = new HashSet<User>();
//getters and setters
}
有关更多信息,请使用hibernate docs http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch07.html