Step by step: JPA's basic additions and deletions check crud (JPA based on hibernate)

Source: Internet
Author: User
1. Create a JPA project

First, create a JPA project (if you do not know that JPA creates or appears in least one user library must be selected, refer to Http://blog.csdn.net/baidu_37107022/article /details/76554393)


Jar Package Description


2. Create entity Classes

description of related annotations in entity classes

* @Table  annotation class corresponding table
 * If table name and type are the same, omit @table, such as Class users and table users;
 * If not the same, must have @table, and set name, for the class corresponding to the table name. @Table (name= "users")
 * * 
 @Entity Callout Entity
 * 
 * * @Id Callout Id * * 
 @Transient Callout This property does not map with the table ( Reason: There may not be a corresponding field in the table for this attribute
 * There is this annotation, the property will not appear when executing the SQL statement, otherwise there will be, if there is no this field in the table will be the error
 * 
 * @Basic Default All properties have this annotation (primary key needs to be used separately @id) , so you can omit
 * 		    The annotation can be placed on the attribute or on the corresponding getter method.
 * 		     Note: Either unify the @basic on the attributes, or place them uniformly on the corresponding getter method. (generally put on the property, readability is good)
 * * 
 @Column class, when the name of the property is not the same as the corresponding field name in the table, the annotation is used to indicate the corresponding field in the class
 * 			@Column (name= "field name in the corresponding table")


Building Entity classes users

Import Javax.persistence.Basic;
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.Id;
Import javax.persistence.Table;
Import javax.persistence.Transient;
 /** * @Table annotation class corresponding table * If table name and type are the same, omit @table, such as Class users and table users; * If not the same, must have @table, and set name, for the class corresponding to the table name. @Table (name= "Users") * * @Entity Callout Entity * * * @Id Callout Id * * @Transient Callout This property does not map with the table (cause: There may not be a field in the table for this property) * There is this annotation, in the execution of SQL
 The property is not present when the otherwise there will be, if the table does not have this field will be an error * * @Basic The default all properties have this annotation (primary key needs to be used separately @id), so you can omit * The annotation can be placed on the attribute or on the corresponding getter method. * Note: Either unify the @basic on the attributes, or place them uniformly on the corresponding getter method. (usually placed on attributes, * * * * * * @Column class with a different property name and a corresponding field name in the table, the annotation is used to indicate the corresponding field in the class * @Column (name= "field name in the corresponding table") */@Table (name= "US
	ERs ") @Entity public class Users {//callout Id @Id private String uid;
	@Basic @Column (name= "uname") private String uname;
	
	@Basic private int age;
	@Transient private String remark;//Note public string Getremark () {return remark; } public void Setremark (String remark) {This.remark = Remark;
	Public String Getuid () {return UID;
	The public void SetUid (String uid) {this.uid = UID;
	Public String Getuname () {return uname;
	} public void Setuname (String uname) {this.uname = uname;
	public int getage () {return age;
	public void Setage (int age) {this.age = age;
	@Override public String toString () {return "Users [uid=" + uid + ", uname=" + uname + ", age=" + Age + "]";
		Public Users (String uid, string uname, int age) {super ();
		This.uid = UID;
		This.uname = uname;
	This.age = age;
		Public Users () {super (); TODO auto-generated Constructor stub}


Configuration of the 3.JPA configuration file Persistence.xml

<?xml version= "1.0" encoding= "UTF-8"?> <persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/" Persistence "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://java.sun.com/xml/ Ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd "> <persistence-unit name=" JPA Transaction-type= "Resource_local" > <!--configuration JPA ORM Products--> <provider> Org.hibernate.jpa.hibernatepersistenceprovider</provider> <!--Add the corresponding persistence class--> <class> Com.java.bean.users</class> <properties> <!--JPA Connection database--> <property name= "javax.persistence . Jdbc.driver "value=" Com.mysql.jdbc.Driver "/> <property name=" Javax.persistence.jdbc.url "value=" Jdbc:mysql ://localhost:3306/jpa "/> <property name=" Javax.persistence.jdbc.user "value=" root "/> <property name=" J Avax.persistence.jdbc.password "value=" 123 ></property> <!--JPA configuration Hibernate basic Properties--> <Property Name= "Hibernate.show_sql" value= "true"/> <property name= "Hibernate.format_sql" value= "true"/>
 ;/properties> </persistence-unit> </persistence>

4. Test additions and deletions to check crud

Import Java.util.HashMap;

Import Java.util.Map;
Import Javax.persistence.EntityManager;
Import Javax.persistence.EntityManagerFactory;
Import javax.persistence.EntityTransaction;

Import javax.persistence.Persistence;

Import Com.java.utils.JPAUtils;

Import Junit.framework.TestCase; public class TestUsers extends TestCase {//Insert data persist equivalent to hibernate save method public void Testinsert () {//1. Get facto
		Ry Entitymanagerfactory factory = persistence.createentitymanagerfactory ("JPA");
		2. Get Manager Entitymanager manager = Factory.createentitymanager ();
		3. Access to business and open Uiwu entitytransaction transaction = Manager.gettransaction ();
		Transaction.begin ();
		4. Execute SQL Users users = new users ("1", "xiaoming", 18);
		Manager.persist (users);
		5. Commit TRANSACTION, close resource Transaction.commit ();
		Manager.close ();
	Factory.close (); /** * The second way to create Entitymanagerfactory is to place the following configuration on the Create factory configuration, using the map * <property name= "Hibernate.show_sql" t Rue "/> <property name= *" Hibernate.formAt_sql "value=" true "/> * * * * When the configuration file and the creation of the factory have the same configuration, you will follow the settings in the created factory/public void TestInsert2 () {//1. Obtained
		Factory Map Properties = new hashmap<string, object> ();
		Properties.put ("Hibernate.format_sql", "false");
		Entitymanagerfactory factory = persistence.createentitymanagerfactory ("JPA", properties);
		2. Get Manager Entitymanager manager = Factory.createentitymanager ();
		3. Access to business and open Uiwu entitytransaction transaction = Manager.gettransaction ();
		Transaction.begin ();
		4. Execute SQL Users users = new users ("2", "Xiaoming 2", 18);
		Manager.persist (users);
		5. Commit TRANSACTION, close resource Transaction.commit ();
		Manager.close ();
	Factory.close (); ///Based on ID query find equivalent to hibernate get method public void Testfind () {//1. Obtain factory Entitymanagerfactory factory = Persiste
		Nce.createentitymanagerfactory ("JPA");
		2. Get Manager Entitymanager manager = Factory.createentitymanager ();
		3. Obtain the transaction and open the transaction entitytransaction transaction = Manager.gettransaction (); Transaction.begiN ();
		4. Execute SQL Users users = Manager.find (Users.class, "1");
		System.out.println (users);
		5. Commit TRANSACTION, close resource Transaction.commit ();
		Manager.close ();
	Factory.close (); ///Based on ID query getreference equivalent to hibernate Load method/Find and GetReference----and the difference between get and load in hibernate---lazy load--id no corresponding value times abnormal PU
		Blic void Testget () {//1. Get factory Entitymanagerfactory factory = Persistence.createentitymanagerfactory ("JPA");
		2. Get Manager Entitymanager manager = Factory.createentitymanager ();
		3. Obtain the transaction and open the transaction entitytransaction transaction = Manager.gettransaction ();
		Transaction.begin (); 
		4. Execute SQL Users users=manager.getreference (users.class, "1");
		System.out.println (users);
		5. Commit TRANSACTION, close resource Transaction.commit ();
		Manager.close ();
	Factory.close (); //Modify Data public void Testupdate () {//1. Get factory entitymanagerfactory factory = Persistence.createentitymanagerf
		Actory ("JPA");
		2. Get Manager Entitymanager manager = Factory.createentitymanager (); 3. Get the transaction and open the transaction ENtitytransaction transaction = Manager.gettransaction ();
		Transaction.begin (); 
		4. Execute SQL Users users=manager.find (users.class, "1");
		Users.setuname ("haha ha 1");
		5. Commit TRANSACTION, close resource Transaction.commit ();
		Manager.close ();

	Factory.close (); //Remove data Remove is equivalent to hibernate Delete method//Remove method can only remove the long object, can not delete the free object public void Testremove () {//1. Get Factory Ent
		Itymanagerfactory factory = persistence.createentitymanagerfactory ("JPA");
		2. Get Manager Entitymanager manager = Factory.createentitymanager ();
		3. Obtain the transaction and open the transaction entitytransaction transaction = Manager.gettransaction ();
		Transaction.begin (); 4. Execute SQL Users users=manager.find (users.class, "2");
		Manager.remove (users);
		5. Commit TRANSACTION, close resource Transaction.commit ();
		Manager.close ();
	Factory.close (); }

}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.