@Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "username") private String username; // Getters and setters } <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="com.example.User"/> </session-factory> </hibernate-configuration> SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); try { User user = new User(); user.setUsername("John Doe"); session.save(user); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); sessionFactory.close(); }


上一篇:
下一篇:
切换中文