0
我有實體:休眠:更新,而不是插入
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name", nullable = false)
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL)
private List<Lesson> lessonList = new ArrayList<>();
....setters/getters
}
我從BD獲得用戶做的xml:
<user>
<name>123</name>
<id>35</id>
</user>
接下來,我從這個XML獲得新用戶,並嘗試在BD保存。
session.save(user);
如果用戶列表lessonList爲空Hibernate在BD中插入NEW用戶。如果列表不爲空Hibernate使用更新。爲什麼?
我使用JAXB
User.class
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name", nullable = false)
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL)
private List<Lesson> lessonList = new ArrayList<>();
....setters/getters
}
與JAXB
創建XML@Transactional
public User getUserFromXML(int id) {
StringWriter stringWriter = new StringWriter();
User copyUser = null;
User user = UserDAO.getById(id);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(user, stringWriter);
StringReader stringReader = new ringReader(stringWriter.toString());
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
copyUser = (User) unmarshaller.unmarshal(stringReader);
} catch (JAXBException e) {
e.printStackTrace();
}
return copyUser;
}
控制器:
@Transactional
void copyUser(HttpServletRequest request, HttpServletResponse response) {
User copyUser = getUserFromXML(idUser);// it get from Client
copyUser.setParentid(getLoginUser());
userDAO.save(copyUser);
}
}
向我們展示您用來測試它的休眠日誌和實際代碼。 – Antoniossss
@Antoniossss我添加了代碼 – Sergei