Hibernate使用Annotations最简单例子:
hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1/testdb root 1 org.hibernate.dialect.MySQL5Dialect thread org.hibernate.cache.internal.NoCacheProvider true update
HibernateUtil.java
package com.my.dao.util;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); return configuration.configure().buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
POJO
package com.my.bean;import java.util.Date;import javax.persistence.*;@Entity@Table(name="user")public class User { @Id @GeneratedValue @Column(name="user_id", nullable=false) private long userID; @Column(name="user_name", length=100, nullable=false) private String userName; @Column(name="create_time", nullable=false) private Date createTime; public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }}
Test:
package com.my.init;import java.util.Date;import org.hibernate.Session;import org.hibernate.Transaction;import com.my.bean.User;import com.my.dao.util.HibernateUtil;public class Test { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); try { User user = new User(); user.setUserName("Robin"); user.setCreateTime(new Date()); session.save(user); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } session.close(); }}
参考文献: