我想使用 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; }
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
@Autowired
SessionFactory sessionFactory;
@Transactional(propagation = Propagation.REQUIRED)
public Boolean EnumObjType(EnumobjType obj) {
boolean flag=false;
int i =(integer)sessionFactory.getCurrentSession().save(obj).intValue();
if (i > 0) {
flag = true;
}
return flag;
}
始终创建单独的 Doa 类来保存对象
添加回答
举报
0/150
提交
取消