1. 程式人生 > >hibernate結合postgresql資料庫在專案中的使用

hibernate結合postgresql資料庫在專案中的使用

新增mvn依賴:

<!-- hibernate dependence -->
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>5.1.0.Final</version>
      </dependency>
<dependency>
          <groupId>org.hibernate.javax.persistence</groupId>
          <artifactId>hibernate-jpa-2.1-api</artifactId>
          <version>1.0.0.Final</version>
      </dependency>
<dependency>
          <groupId>org.hibernate.common</groupId>
          <artifactId>hibernate-commons-annotations</artifactId>
          <version>5.0.1.Final</version>
      </dependency>
<dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>5.0.1.Final</version>
      </dependency>
      <!-- postgresql dependence -->
      <dependency>
          <groupId>org.postgresql</groupId>
          <artifactId>postgresql</artifactId>
          <!-- <version>9.4-1201-jdbc41</version> -->
          <version>9.4.1208.jre7</version>
      </dependency>

實現hibernate的實體類和對映關係

新增postgresql的config檔案hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url."/>
        <property name="connection.driver_class"/>
        <property name="connection.username"/>
        <property name="connection.password"/>
        <!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

先實現一個session工廠物件類SessionFactoryUtil.java

public class SessionFactoryUtil {
	private volatile static SessionFactoryUtil m_UtilInstance = null;
	private static SessionFactory m_SessionFactory= null;
  	public final String CONFIG_FILE = "hibernate2.cfg.xml";
	private SessionFactoryUtil(){
		try{
			String rcPath = this.getClass().getClassLoader().getResource("./").getPath();
			//String rcPath = "/app/web/m2m-core/leshan-server-orm/src/main/resources";
			//String path = String.format("%1$s/%2$s", System.getProperty("user.dir"), CONFIG_FILE);
			String path = String.format("%1$s/%2$s", rcPath, CONFIG_FILE);
			File file = new File(path);
			StandardServiceRegistry  serviceRegistry = null;
			if(file.exists()){
         		serviceRegistry=new StandardServiceRegistryBuilder().configure(file).build();  
          	}else
          		serviceRegistry=new StandardServiceRegistryBuilder().configure().build();  
      		m_SessionFactory=new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static SessionFactoryUtil getInstance(){
		if(m_UtilInstance == null){
			synchronized(SessionFactoryUtil.class){
				if(m_SessionFactory == null){
					m_UtilInstance = new SessionFactoryUtil();
				}
			}
		}
		return m_UtilInstance;
	}
	
	public SessionFactory getSessionFactory(){
		return m_SessionFactory;
	}
	
	public static void closeSessionFactory(){
		if(m_SessionFactory != null){
			m_SessionFactory.close();
			m_SessionFactory = null;
			m_UtilInstance = null;
		}
	}
}

再實現一個實體類user

public class User implements java.io.Serializable {

	private long uid;
	private String name;
	private String passwd;
	private Long ts;

	private User() {
	}

	private User(long uid) {
		this.uid = uid;
	}
	
	public User(String name, String passwd) {
		this.name = name;
		this.passwd = passwd;
	}

	@Id
	@SequenceGenerator(name = "user_uid_seq", allocationSize = 1, initialValue = 1, sequenceName = "user_uid_seq")  
	@GeneratedValue(generator = "user_uid_seq", strategy = GenerationType.SEQUENCE)
	@Column(name = "uid", unique = true, nullable = false)
	public long getUid() {
		return this.uid;
	}

	private void setUid(long uid) {
		this.uid = uid;
	}

	@Column(name = "name", unique = true, length = 256)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name = "passwd", length = 256)
	public String getPasswd() {
		return this.passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	@Column(name = "ts")
	public Long getTs() {
		return this.ts;
	}

	public void setTs(Long ts) {
		this.ts = ts;
	}
}

 最後實現介面userbean.java

public class UserBean implements IUserBean{
	@Override
	public boolean insertUser(User user){
		if(null == user) return false;
		try{
			SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
	        Session session = sessionFactory.openSession(); 
	        Transaction tx = session.beginTransaction();  
			Date dt = new Date();
			user.setTs(dt.getTime());
	        session.save(user);
	        tx.commit();
	        session.close();
		}
		catch (Exception e){
			System.out.println(e.getMessage()); 
            System.out.printf("===========================\n");  
            e.printStackTrace();
			return false;
		}
        return true;
	}
	@Override
	public boolean deleteUserByUserName(String name){
		boolean nRet = false;
		if(null == name || "" == name)return nRet;
		SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
        Session session = sessionFactory.openSession(); 
        Transaction tx = session.beginTransaction();  
        try{
        	String hql="delete User as d where d.name=?";
        	Query query=session.createQuery(hql);
        	query.setParameter(0, name);
        	int tmpValue = query.executeUpdate();
        	System.out.println("[UserBean]Result of query " + String.valueOf(tmpValue));
            tx.commit();
            nRet = true;
        }catch(Exception ex){
        	System.out.println("[UserBean] test delete exception" + ex.toString());
        	nRet = false;
        	if(tx != null) tx.rollback();
        	session.close();
        }
        session.close();
		return nRet;
	}
	@Override
	public boolean deleteUserAll(){
		boolean nRet = false;
		SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
        Session session = sessionFactory.openSession(); 
        Transaction tx = session.beginTransaction();  
        try{
        	String hql="delete from User";
        	Query query=session.createQuery(hql);
        	int tmpValue = query.executeUpdate();
        	System.out.println("[UserBean]Result of query " + String.valueOf(tmpValue));
            tx.commit();
            nRet = true;
        }catch(Exception ex){
        	System.out.println("[UserBean] test delete exception" + ex.toString());
        	nRet = false;
        	if(tx != null) tx.rollback();
        	session.close();
        }
        session.close();
		return nRet;
	}
	@Override
	public boolean updateUser(User user){
		boolean nRet = false;
		if(user == null)return nRet;
		SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
        Session session = sessionFactory.openSession(); 
        Transaction tx = session.beginTransaction();  
        try{
          	String hql="select count(*) from User as d where d.uid=?";
          	Query query=session.createQuery(hql).setParameter(0, user.getUid());
          	long ret = (Long) query.uniqueResult();
          	if(ret > 0){
          		session.update(user);
          		tx.commit();
          		nRet = true;
          	}else nRet = false;
        }catch(Exception ex){
        	System.out.println("[UserBean] test delete exception" + ex.toString());
        	nRet = false;
        	if(tx != null) tx.rollback();
        	session.close();
        }
        session.close();
		return nRet;
	}
	@Override
	public User[] getUserAll(){
		List<User> list = new ArrayList<User>();
		User[] userArray = null;
		SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
        Session session = sessionFactory.openSession(); 
        try{
        	list = (List<User>)session.createQuery("select d from User d").list();
        	userArray = (User[])list.toArray(new User[0]);
        }catch(Exception ex){
        	userArray = (User[])list.toArray(new User[0]);
          	System.out.println("[UserBean][getUserAll] exception" + ex.toString());
          	session.close();
        }
        session.close();
		return userArray;
	}
	@Override
	public User getUserByUserName(String name){
		List<User> list = new ArrayList<User>();
		User user = null;
		if(null == name || "" == name)return user;
		SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
        Session session = sessionFactory.openSession(); 
        try{
        	list = (List<User>)session.createQuery("select d from User d where d.name=?").setString(0, name).list();
        	if(list.size()>0) user = list.get(0);
        }catch(Exception ex){
          	System.out.println("[UserBean][getUserAll] exception" + ex.toString());
          	session.close();
        }
        session.close();
		return user;
	}
}