我想使用 Java 和 Hibernate 將新創(chuàng)建的對(duì)象保存到數(shù)據(jù)庫(kù)中。對(duì)于一個(gè)簡(jiǎn)單的對(duì)象,在其構(gòu)造函數(shù)中將其存儲(chǔ)在數(shù)據(jù)庫(kù)中是一種不好的做法嗎?如果是這樣,為什么?我應(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; }
在類構(gòu)造函數(shù)中將對(duì)象保存到數(shù)據(jù)庫(kù)是一種不好的做法嗎?
炎炎設(shè)計(jì)
2023-12-13 16:27:48