- db table
CREATE TABLE Dbuser
(
USER_ID NUMBER(5) NOT NULL,
USERNAME VARCHAR2(20) ,
CREATED_BY VARCHAR2(20) ,
CREATED_DATE DATE
)
- hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@DbServer:port:sid</property>
<property name="hibernate.connection.username">***</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="config/mapping/oneConfig/Dbuser.hbm.xml" />
</session-factory>
</hibernate-configuration>
- Dbuser.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2013-10-22 15:28:34 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="pojo.oneConfig.Dbuser" table="DBUSER" >
<id name="userId" type="int">
<column name="USER_ID" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="20" />
</property>
<property name="createdBy" type="string">
<column name="CREATED_BY" length="20" />
</property>
<property name="createdDate" type="date">
<column name="CREATED_DATE" length="7" />
</property>
</class>
</hibernate-mapping>
- POJO
package pojo.oneConfig;
import java.util.Date;
public class Dbuser {
private int userId;
private String username;
private String createdBy;
private Date createdDate;
public Dbuser() {
}
public Dbuser(int userId) {
this.userId = userId;
}
public Dbuser(String name, int id) {
this.userId = id;
this.username = name;
}
public Dbuser(int userId, String username, String createdBy, Date createdDate) {
this.userId = userId;
this.username = username;
this.createdBy = createdBy;
this.createdDate = createdDate;
}
//getter and setter
}
- HibernateUtil
package config.hibernate.oneConfig;
import org.hibernate.SessionFactory;
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
return new Configuration().configure().buildSessionFactory();
} 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;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
- Test case
package main.oneConfig;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import config.hibernate.oneConfig.HibernateUtil;
import pojo.oneConfig.Dbuser;
public class Main {
static SessionFactory factory;
public static void main(String[] args) {
factory = HibernateUtil.getSessionFactory();
Dbuser dbuser = new Dbuser();
dbuser.setCreatedBy("yz20537");
dbuser.setCreatedDate(new Date());
dbuser.setUserId(202);
dbuser.setUsername("hahaha");
// add(dbuser);
// query();
// update(201, "aaaa");
// delete(201);
// testHql();
testCriteria();
// testNativeSql();
}
static void add(Dbuser dbuser) {
Session session = factory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(dbuser);
transaction.commit();
} catch (Exception ex) {
ex.printStackTrace();
transaction.rollback();
} finally {
if (session != null) {
session.close();
}
}
}
static void query() {
Session session = factory.openSession();
try {
// List result = session.createQuery("from Dbuser").list();
List result = session.createSQLQuery("select * from dbuser").addEntity(Dbuser.class).list();
for (Object object : result) {
Dbuser dbuser = (Dbuser) object;
System.out.println(String.format("%s %s", dbuser.getUserId(), dbuser.getUsername()));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
static void update(int id, String name) {
Session session = factory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Dbuser dbuser = (Dbuser) session.get(Dbuser.class, id);
dbuser.setUsername(name);
session.update(dbuser);
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
} finally {
if (session != null) {
session.close();
}
}
}
static void delete(int id) {
Session session = factory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Dbuser dbuser = (Dbuser) session.get(Dbuser.class, id);
session.delete(dbuser);
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
} finally {
if (session != null) {
session.close();
}
}
}
static void testHql() {
Session session = factory.openSession();
try {
/*Query query = session.createQuery("from Dbuser");
List result = query.list();
for (Object object : result) {
System.out.println(((Dbuser) object).getUsername());
}*/
/*Query query = session.createQuery("select u.username from Dbuser as u");
List result = query.list();
for (Object object : result) {
System.out.println(object.toString());
}*/
/*Query query = session.createQuery("select u.username,u.userId from Dbuser as u");
List<Object[]> result = query.list();
for (Object[] objects : result) {
System.out.print(objects[0].toString());
System.out.println(objects[1].toString());
}*/
/*Query query = session.createQuery("select new Dbuser(u.username,u.userId) from Dbuser as u");
List<Dbuser> result = query.list();
for (Dbuser i : result) {
System.out.println(i.getUsername() + "," + i.getUserId());
}*/
/*Query query = session.createQuery("select new Dbuser(u.username,u.userId) from Dbuser as u where u.userId=101");
List<Dbuser> result = query.list();
for (Dbuser i : result) {
System.out.println(i.getUsername() + "," + i.getUserId());
}*/
/*Query query = session.createQuery("select sum(u.userId),u.username from Dbuser as u group by u.username");
List<Object[]> result = query.list();
for (Object[] objects : result) {
System.out.print(objects[0].toString() + ",");
System.out.println(objects[1].toString());
}*/
/*Query query = session.createQuery("from Dbuser");
List result = query.setFirstResult(1).setMaxResults(2).list();// 0(no),1(yes),2(yes)
for (Object object : result) {
System.out.println(((Dbuser) object).getUsername());
}*/
/*Transaction transaction = session.beginTransaction();
Query query = session.createQuery("update Dbuser as u set u.username= :username where u.userId=:userId").setParameter("username", "newName1").setParameter("userId", 101);
int result = query.executeUpdate();
transaction.commit();
System.out.println(result);*/
/*Transaction transaction = session.beginTransaction();
Query query = session.createQuery("delete from Dbuser u where u.userId = :userId").setParameter("userId", 202);
System.out.println(query.executeUpdate());
transaction.commit();*/
} finally {
session.close();
}
}
static void testCriteria() {
Session session = factory.openSession();
try {
Criteria criteria = session.createCriteria(Dbuser.class);
/*
* HashMap<String, Object> matches = new HashMap<String, Object>();
* matches.put("userId", 100); matches.put("username", "aa");
* criteria.add(Restrictions.allEq(matches));
*/
criteria.add(Restrictions.between("userId", 100, 101));
// criteria.add(Restrictions.idEq(100));
// criteria.add(Restrictions.ilike("username", "nEw%")); // like ignore case
// criteria.add(Restrictions.in("userId", Arrays.asList(100,101)));
// criteria.add(Restrictions.isEmpty("createdBy"));//not work @@@ Property path [yz20537.hibernate_test.Dbuser.createdBy] does not reference a collection
// criteria.add(Restrictions.isNotEmpty("createdBy"));//not work @@@
// criteria.add(Restrictions.isNotNull("createdBy"));
// criteria.add(Restrictions.isNull("createdBy"));
// criteria.add(Restrictions.sqlRestriction("CREATED_BY is null"));
// criteria.add(Restrictions.eq("userId", 100)); // =
// criteria.add(Restrictions.eqProperty("username", "createdBy")); //=
// criteria.add(Restrictions.ge("userId", 100));// >=
// criteria.add(Restrictions.geProperty("username", "createdBy")); //>=
// criteria.add(Restrictions.gt("userId", 100));// >
// criteria.add(Restrictions.gtProperty("username", "createdBy")); //>
// criteria.add(Restrictions.le("userId", 100));// >=
// criteria.add(Restrictions.leProperty("username", "createdBy")); // >=
// criteria.add(Restrictions.lt("userId", 100));// >
// criteria.add(Restrictions.ltProperty("username", "createdBy")); //>
// criteria.add(Restrictions.ne("createdBy", "null")); // !=
// criteria.add(Restrictions.neProperty("username", "createdBy"));// 字段不可为null
// criteria.add(Restrictions.and(Restrictions.eq("username", "aa"),Restrictions.eq("userId", 1001))); //and
// criteria.add(Restrictions.or(Restrictions.eq("username", "aa"),Restrictions.eq("userId", 1001))); // or
// criteria.addOrder(Order.desc("username")); // order by
// criteria.setFirstResult(0).setMaxResults(2);// pager
List<Dbuser> result = criteria.list();
for (Dbuser dbuser : result) {
System.out.println(dbuser.getUserId() + "," + dbuser.getUsername());
}
/*List result = criteria.setProjection(Projections.rowCount()).list();
for (Object object : result) {
System.out.println((Long)object);
}*/
/*List result = criteria.setProjection(Projections.avg("userId")).list();
for (Object object : result) {
System.out.println((Double) object);
}*/
/*List result = criteria.setProjection(Projections.countDistinct("userId")).list();
for (Object object : result) {
System.out.println((Long) object);
}*/
/*List result = criteria.setProjection(Projections.max("username")).list();
for (Object object : result) {
System.out.println((String) object);
}*/
/*List result = criteria.setProjection(Projections.min("userId")).list();
for (Object object : result) {
System.out.println((Integer) object);
}*/
/*List result = criteria.setProjection(Projections.sum("userId")).list();
for (Object object : result) {
System.out.println((Long) object);
}*/
} finally {
session.close();
}
}
static void testNativeSql() {
Session session = factory.openSession();
SQLQuery query = session.createSQLQuery("select * from Dbuser").addEntity(Dbuser.class);
List result = query.list();
for (Object object : result) {
Dbuser dbuser = (Dbuser) object;
System.out.println(dbuser.getUserId() + "," + dbuser.getUsername());
}
/*SQLQuery query = session.createSQLQuery("select username,user_id from Dbuser");
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List result = query.list();
for (Object object : result) {
HashMap<String, Object> row = (HashMap<String, Object>) object;
System.out.println(row.get("USERNAME") + "," + row.get("USER_ID"));
}*/
}
}
改成注解的版本:
- hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@DbServer:port:sid</property>
<property name="hibernate.connection.username">***</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="pojo.oneAnnotation.Dbuser" />
</session-factory>
</hibernate-configuration>
- POJO
package pojo.oneAnnotation;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Dbuser")
public class Dbuser {
@Id
@Column(name = "USER_ID")
private int userId;
@Column(name = "USERNAME")
private String username;
@Column(name = "CREATED_BY")
private String createdBy;
@Column(name = "CREATED_DATE")
private Date createdDate;
public Dbuser() {
}
public Dbuser(int userId) {
this.userId = userId;
}
public Dbuser(String name, int id) {
this.userId = id;
this.username = name;
}
public Dbuser(int userId, String username, String createdBy, Date createdDate) {
this.userId = userId;
this.username = username;
this.createdBy = createdBy;
this.createdDate = createdDate;
}
//getter and setter
}