添加mvn依赖:
org.hibernate
hibernate-core
5.1.0.Final
org.hibernate.javax.persistence
hibernate-jpa-2.1-api
1.0.0.Final
org.hibernate.common
hibernate-commons-annotations
5.0.1.Final
org.hibernate
hibernate-validator
5.0.1.Final
org.postgresql
postgresql
9.4.1208.jre7
实现hibernate的实体类和映射关系
添加postgresql的config文件hibernate.cfg.xml
先实现一个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 list = new ArrayList();
User[] userArray = null;
SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
Session session = sessionFactory.openSession();
try{
list = (List)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 list = new ArrayList();
User user = null;
if(null == name || "" == name)return user;
SessionFactory sessionFactory = SessionFactoryUtil.getInstance().getSessionFactory();
Session session = sessionFactory.openSession();
try{
list = (List)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;
}
}