【问题标题】:SpringDataJpa many-to-one gives NULLSpring Data Jpa 多对一给出 NULL
【发布时间】:2014-07-29 21:12:13
【问题描述】:

我的实体有问题。我已经通过交易在这两个实体之间建立了多对一的连接。我就是这样做的:

User user = new User();
    user.setName("a");
    user.setLastName("b");
    Set<Adress> a = new HashSet<Adress>();
    Adress a1 = new Adress();
    Adress a2 = new Adress();
    a1.setCity("a1");
    a2.setCity("a2");
    a.add(a1);
    a.add(a2);
    user.setAdress(a);
    userProxy.save(user);

我的实体:

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;

@NotNull
private String name;

@NotNull
private String lastName;

@OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private Set<Adress> adress = new HashSet<Adress>();

public User(String name, String lastName) {
    this.name = name;
    this.lastName = lastName;
}

public User() {

}

public Set<Adress> getAdress() {
    return adress;
}

public void setAdress(Set<Adress> adress) {
    this.adress = adress;
}

public String getName() {
    return name;
}

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

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Long getId() {
    return id;
}
}

第二个实体

@Entity
public class Adress {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private Long id;

private String city;

@ManyToOne
@JoinColumn(name="user_id")
private User user;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public Long getId() {
    return id;
}

}

用户表中的数据保存得很好,但在表地址字段中,user_id 为“NULL”,谁能向我解释这是为什么?我已经尝试了很多与 @ManyToOne 的组合,但对我没有任何效果。

更多详情用户代理:

@Service
public class UserProxyDao {

private UserDao userDao;

@Autowired
public UserProxyDao(UserDao userDao) {
    this.userDao = userDao;
}

public void save(User user) {
    userDao.save(user);
}
}

但是,如果我在地址实体验证中将@NotNull 放在字段用户上...我真的不知道这是为什么

Caused by: javax.validation.ConstraintViolationException: validation failed for classes [pl.rd.j2ee.api.domain.Adress] during persist time for groups [javax.validation.groups.Default, ]

【问题讨论】:

  • 好吧,我认为您必须先发送保存地址,然后再与用户一起发送,因为您没有 ID(我不记得理论,但我认为是这样)
  • 但我的意思是像一个动作一样保存用户的地址。我不想单独这样做。

标签: spring hibernate spring-data-jpa many-to-one


【解决方案1】:

只要您先执行此操作,您应该可以在一个操作中执行此操作。

a1.setUser(user);
a2.setUser(user);

您总是可以将User 添加到您的Address 构造函数并在那里执行。

public Address (User user) {
    this.user = user;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2016-01-31
    • 2015-05-10
    相关资源
    最近更新 更多