我想使用 Java 和 Hibernate 將新創(chuàng)建的對象保存到數(shù)據(jù)庫中。對于一個簡單的對象,在其構(gòu)造函數(shù)中將其存儲在數(shù)據(jù)庫中是一種不好的做法嗎?如果是這樣,為什么?我應(yīng)該怎么做呢?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條經(jīng)驗 獲得超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;
}
始終創(chuàng)建單獨的 Doa 類來保存對象
添加回答
舉報
0/150
提交
取消