QBC query of Hibernate

Posted by Nat on Mon, 02 Dec 2019 14:56:22 +0100

Customer.java

public class Customer {
	
	public Customer() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public Customer(String cust_name, String cust_source) {
		super();
		this.cust_name = cust_name;
		this.cust_source = cust_source;
	}

	private Long cust_id;
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_phone;
	private String cust_mobile;
	//Represented by ORM: multiple contacts corresponding to a customer
	//A collection of multiple prevented parties. Hibernate uses Set sets by default
	private Set<LinkMan> linkMans=new HashSet<LinkMan>();
    //Omit get and set methods
}

LinkMan.java

public class LinkMan {
	private Long lkm_id;
	private String lkm_name;
	private String lkm_gender;
	private String lkm_phone;
	private String lkm_mobile;
	private String lkm_email;
	private String lkm_qq;
	private String lkm_position;
	private String lkm_memo;
	//By ORM: a contact can only belong to one customer
	//Objects placed on one side
	private Customer customer;
    //Omit get and set methods
}

Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.hibernate.domain.Customer" table="cst_customer">
		<! -- create OID and primary key mapping -- >
		<id name="cust_id" column="cust_id">
			<generator class="native"/>
		</id>
		<! -- establish correspondence between common properties and fields in the table -- >
		<property name="cust_name" column="cust_name"/>
		<property name="cust_source" column="cust_source"/>
		<property name="cust_industry" column="cust_industry"/>
		<property name="cust_level" column="cust_level"/>
		<property name="cust_phone" column="cust_phone"/>
		<property name="cust_mobile" column="cust_mobile"/>
		<! -- configure one to many mapping: a set of placed many sides -- >
		<!-- 
			set Tags
				*Name: the attribute name of the object collection of multiple parties
				*Cascade: cascade
				*inverse: give up the maintenance right of foreign key default false: do not give up
		 -->
		<set name="linkMans">
			<!-- 
				key Tags
					*column: the name of the foreign key of more than one party
			 -->
			<key column="lkm_cust_id"/>
			<!-- 
				One to many label
					*class: the full path of multiple parties
			 -->
			<one-to-many class="com.hibernate.domain.LinkMan"/>
		</set>
	</class>
</hibernate-mapping>

LinkMan.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.hibernate.domain.LinkMan" table="cst_linkman">
		<! -- create OID and primary key mapping -- >
		<id name="lkm_id" column="lkm_id">
			<generator class="native"/>
		</id>
		<! -- create mapping between common attributes and table fields -- >
		<property name="lkm_name"/>
		<property name="lkm_gender"/>
		<property name="lkm_phone"/>
		<property name="lkm_mobile"/>
		<property name="lkm_email"/>
		<property name="lkm_qq"/>
		<property name="lkm_position"/>
		<property name="lkm_memo"/>
		<! -- configure many to one relationship: objects placed on one side -- >
		<!-- 
			Many to one tag
				*Name: property name of one party's object
				*class: the full path of one party
				*column: the name of the foreign key of the table on more than one side
		 -->
		 <many-to-one name="customer" cascade="save-update,delete" class="com.hibernate.domain.Customer" column="lkm_cust_id"/>
	</class>
</hibernate-mapping>

HibernateUtils.java

public class HibernateUtils {

	public static final Configuration cfg;
	public static final SessionFactory sf;
	
	static{
		cfg = new Configuration().configure();
		sf = cfg.buildSessionFactory();
	}
	
	public static Session openSession(){
		return sf.openSession();
	}
	
	public static Session getCurrentSession() {
		return sf.getCurrentSession();//Need configuration
	}
}

hibernate.cfg.xml under src

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Basic parameters of connecting database -->
		<!-- hibernate-release-5.0.7.Final\project\etc\hibernate.properties -->
		<!-- localhost:3306 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day04</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">password</property>
		<!-- To configure Hibernate Dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<!-- ==========Optional configuration========= -->
		<!-- Printing sql -->
		<property name="hibernate.show_sql">true</property>
		<!-- Format sql -->
		<property name="hibernate.format_sql">true</property>
		<!-- Automatic table building create update -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- Set transaction isolation level -->
		<!-- 
			1 read uncommitted  :Dirty reading, non repeatable reading and virtual reading all happen
			2 read committed    :Solve dirty reading  (oracle default)
			4 repeatable read   :Solving dirty and non repeatable reading(mysql default)
			8 serializable      :Solve all problems. Serial execution, low efficiency
		 -->
		<property name="hibernate.connection.isolation">4</property>
		<!-- Configure the Session -->
		<!-- No need session.close() -->
		<property name="hibernate.current_session_context_class">thread</property>
		
		<!-- Introducing mapping -->
		<mapping resource="com/hibernate/domain/Customer.hbm.xml"/>
		<mapping resource="com/hibernate/domain/LinkMan.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

Test class


import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import com.hibernate.domain.Customer;
import com.hibernate.domain.LinkMan;
import com.hibernate.utils.HibernateUtils;

/**
 * QBC Queries
 * @author zhang
 *
 */
public class HibernateDemo2 {

	@Test
	/**
	 * Simple query
	 */
	public void demo1() {
		Session session=HibernateUtils.getCurrentSession();
		Transaction tx=session.beginTransaction();
		
		//Get the object of Criteria
		Criteria criteria = session.createCriteria(Customer.class);
		List<Customer> list=criteria.list();
		
		for (Customer customer : list) {
			System.out.println(customer);
		}
		tx.commit();
	}
	
	@Test
	/**
	 * Sort query
	 */
	public void demo2() {
		Session session=HibernateUtils.getCurrentSession();
		Transaction tx=session.beginTransaction();
		
		//Sort query
		Criteria criteria = session.createCriteria(Customer.class);
//		Criteria. Addorder (order. ASC ("cust" ID)); / / ascending
		criteria.addOrder(Order.desc("cust_id"));
		List<Customer> list=criteria.list();
		
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		tx.commit();
	}
	
	@Test
	/**
	 * Paging query
	 */
	public void demo3() {
		Session session=HibernateUtils.getCurrentSession();
		Transaction tx=session.beginTransaction();
		
		//Paging query
		Criteria criteria = session.createCriteria(LinkMan.class);
		criteria.setFirstResult(10);
		criteria.setMaxResults(10);
		List<LinkMan> list = criteria.list();
		
		for (LinkMan linkMan : list) {
			System.out.println(linkMan);
		}
		tx.commit();
	}
	
	@Test
	/**
	 * Conditional query
	 */
	public void demo4() {
		Session session=HibernateUtils.getCurrentSession();
		Transaction tx=session.beginTransaction();
		
		//Conditional query
		Criteria criteria = session.createCriteria(Customer.class);
		//Setting conditions
		/**
		 *  ==  eq
		 *  >   gt
		 *  >=  ge
		 *  <   lt
		 *  <=  le
		 *  <>  ne
		 *  like
		 *  in
		 *  and
		 *  or
		 */
		criteria.add(Restrictions.eq("cust_source", "Computer"));
//		Criteria. Add (restrictions. Or (restrictions. Like ("cust'u name", "Li%"));
		criteria.add(Restrictions.like("cust_name", "Plum%"));//Juxtaposition of two conditions
		List<Customer> list = criteria.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		tx.commit();
	}
	
	@Test
	//Statistical query
	public void demo5() {
		Session session=HibernateUtils.getCurrentSession();
		Transaction tx=session.beginTransaction();
		
		Criteria criteria = session.createCriteria(Customer.class);
		/**
		 * add				:Common condition
		 * addOrder			:sort
		 * setProjection	:Aggregate function and group by having
		 */
		criteria.setProjection(Projections.rowCount());
//		Object object = criteria.uniqueResult();
		Long num=(Long) criteria.uniqueResult();
		System.out.println(num);
		tx.commit();
	}
	
	@Test
	/**
	 * Offline condition query
	 */
	public void demo6() {
        //web level
		DetachedCriteria detachedCriteria=DetachedCriteria.forClass(Customer.class);
		detachedCriteria.add(Restrictions.like("cust_name", "Plum%"));
		

        //dao level
		Session session=HibernateUtils.getCurrentSession();
		Transaction transaction=session.beginTransaction();
		
		Criteria criteria = detachedCriteria.getExecutableCriteria(session);
		List<Customer> list = criteria.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		transaction.commit();
	}
}

If you feel like this query, it has a big gap with SQL and is more inclined to object-oriented.

Topics: Hibernate Session xml Java