我想使用 Java 和 Hibernate 将新创建的对象保存到数据库中。对于一个简单的对象,在其构造函数中将其存储在数据库中是一种不好的做法吗?如果是这样,为什么?我应该怎么做呢?
public class EnumObjType implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CAR_ID")
private Long CarId;
@NotNull
@Column(name = "NAME")
private String name;
public Car() {
}
public Car(String name, boolean persist) {
setName(name);
if (persist == true) {
setCarId(DB.saveEntity(this));
}
}
// getters and setters
}
DB.class(摘录):
public static <Obj> Long saveEntity(Obj obj) {
Long id;
try {
DB.s.close();
DB.openSession();
DB.s.beginTransaction();
id = (Long) DB.s.save(obj);
DB.s.getTransaction().commit();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
return id;
}
慕姐8265434
相关分类