java一对多和多对一双向关联

注意要加mappedBy

package hibernate002test.copy;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Groups {
private int id;
private String name;
private Set user = new HashSet();

@Id
@GeneratedValue
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@OneToMany(mappedBy="group")    
public Set getUser() {
    return user;
}

public void setUser(Set user) {
    this.user = user;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}
package hibernate002test.copy;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class User {

private int userid;
private String username;
private Groups group;

@ManyToOne
public Groups getGroup() {
    return group;
}

public void setGroup(Groups group) {
    this.group = group;
}

@Id
@GeneratedValue
public int getUserid() {
    return userid;
}

public void setUserid(int userid) {
    this.userid = userid;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

}
测试类
package datatest;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
* 在一对一双向关联时要使用例如:@OneToOne(mappedBy=”wife”)
* @author Lenovo
*
*/
public class Test {

@org.junit.Test
public void test() {
   new SchemaExport(new AnnotationConfiguration().configure()).create(false,true);
}

}

你可能感兴趣的:(hibernate)