Spring learning --- configure and use JPA, spring learning --- jpa

Source: Internet
Author: User

Spring learning --- configure and use JPA, spring learning --- jpa

Theoretical things will never become their own things if they are not put into practice. This article describes how to use maven to manage, use Hibernate as the JPA supplier, use MYSQL database, and configure and use JPA.

The following code has been uploaded to GITHUB.

First, add the dependency to the pom. xml file:

<Dependencies> <! -- Add necessary dependencies to pom --> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-orm </artifactId> <version> 4.0.5.RELEASE </version> </dependency> <groupId> org. springframework </groupId> <artifactId> spring-context </artifactId> <version> 4.0.5.RELEASE </version> </dependency> <groupId> org. springframework </groupId> <artifactId> spring-test </artifactId> <version> 4.0.5.RELE ASE </version> </dependency> <groupId> junit </groupId> <artifactId> junit </artifactId> <version> 4.12 </version> </dependency> <! -- Use Hibernate as a jpa provider --> <dependency> <groupId> org. hibernate </groupId> <artifactId> hibernate-core </artifactId> <version> 4.3.1.Final </version> </dependency> <groupId> org. hibernate </groupId> <artifactId> hibernate-entitymanager </artifactId> <version> 4.3.1.Final </version> </dependency> <! -- Use mysql database, mysql driver required --> <dependency> <groupId> mysql </groupId> <artifactId> mysql-connector-java </artifactId> <version> 5.1.31 </version> </dependency> </dependencies>

Configure 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 = "myJPA" transaction-type = "RESOURCE_LOCAL"> <provider> org. hibernate. ejb. hibernatePersistence </provider> <class> com. domain. user </CIA Ss> <properties> <! -- Configure the Hibernate dialect --> <property name = "hibernate. dialect" value = "org. hibernate. dialect. MySQL5Dialect"/> <! -- Configure the database Driver --> <property name = "hibernate. connection. driver_class" value = "com. mysql. jdbc. Driver"/> <! -- Configure the database username --> <property name = "hibernate. connection. username" value = "root"/> <! -- Configure the Database password --> <property name = "hibernate. connection. password" value = "000"/> <! -- Configure Database url --> <property name = "hibernate. connection. url" value = "jdbc: mysql: // localhost: 3306/jpa? UseUnicode = true & amp; characterEncoding = UTF-8 "/> <! -- Set the maximum depth of the Spanning Tree captured by external connections --> <property name = "hibernate. max_fetch_depth" value = "3"/> <! -- Automatically output the DDL statement for schema Creation --> <property name = "hibernate. hbm2ddl. auto "value =" update "/> <property name =" hibernate. show_ SQL "value =" true "/> <property name =" hibernate. format_ SQL "value =" true "/> <property name =" javax. persistence. validation. mode "value =" none "/> </properties> </persistence-unit> </persistence>

Note that the persistence. xml should be placed in the META-INF directory, persistence. xml is the main entry of JPA configuration, of course, after the combination of spring, you can not use the persistence. xml file.

JPA has two transaction modes: RESOURCE_LOCAL and JTA. I still don't know much about transactions. After I have a deep understanding, I will come back to fill in the issue/***** <p> ClassName: Driver. java <p> * <p> driver Entity class <p> * @ author linzj * @ createTime 10:07:57 on April 9, March 17, 2016 */@ Entity @ Table (name = "driver ") public class Driver {@ Id @ GeneratedValue private Long id; @ Column (name = "firstname") private String firstName; @ Column (name = "lastname") private String lastName; @ onetoetype (cascade = CascadeType. ALL) // propagation persistence @ JoinColumn (name = "dirver_id") private Set <Car> cars = new HashSet <Car> (); public Long getId () {return id ;} public void setId (Long id) {this. id = id;} public String getFirstName () {return firstName;} public void setFirstName (String firstName) {this. firstName = firstName;} public String getLastName () {return lastName;} public void setLastName (String lastName) {this. lastName = lastName;} public Set <Car> getCars () {return cars;} public void setCars (Set <Car> cars) {this. cars = cars ;}@ Override public String toString () {return "Driver [id =" + id + ", firstName =" + firstName + ", lastName = "+ lastName +", cars = "+ cars +"] ";}}/***** <p> ClassName: Car. java <p> * <p> automotive <p> * @ author linzj * @ createTime 9:35:01 on April 9, March 17, 2016 */@ Entity @ Table (name = "car ") public class Car {@ Id @ GeneratedValue private Long id; @ Column (name = "name") private String name; public Long getId () {return id ;} public void setId (Long id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}@ Override public String toString () {return "Car [id =" + id + ", name =" + name + "]" ;}}

As mentioned above, cascade = CascadeType. ALL is persistent for propagation. As the name suggests, when a Dirver object is persisted, the program will also persist the car object in the driver object.

Create a test class:

/*** Create an object management factory class and Test whether the factory is in the Enabled state */@ Test public void openTest () {EntityManagerFactory entityManagerFactory = Persistence. createEntityManagerFactory ("myJPA"); System. out. println ("whether the factory class is Enabled:" + entityManagerFactory. isOpen ();}/*** create an instance and perform a Persistence Test */@ Test public void addTest () {EntityManagerFactory entityManagerFactory = Persistence. createEntityManagerFactory ("myJPA"); // create the object management object EntityManager entityManager = entityManagerFactory. createEntityManager (); // create a new transaction. Remember to enable EntityTransaction entityTransaction = entityManager. getTransaction (); entityTransaction. begin (); // create a Driver object and two Car objects Driver = new driver (); Driver. setFirstName ("taylor"); driver. setLastName ("swift"); Car carOne = new Car (); carOne. setName ("BMW"); Car carTwo = new Car (); carTwo. setName ("AUDI"); // Add the car to the driver set and use EntityManager for persistent driver. getCars (). add (carOne); driver. getCars (). add (carTwo); entityManager. persist (driver); // submit the transaction and disable EntityManager entityTransaction. commit (); entityManager. close ();}/*** use JPA to query objects */@ Test public void findTest () {EntityManagerFactory emf = Persistence. createEntityManagerFactory ("myJPA"); EntityManager em = emf. createEntityManager (); EntityTransaction et = em. getTransaction (); et. begin (); Driver driver = em. find (Driver. class, 1L); Car car = em. getReference (Car. class, 2L); driver. setFirstName ("justin"); em. remove (car); et. commit (); em. close ();}

JPA provides two different query methods: find () and getReference (). The find method causes the entity to be obtained and returns immediately. If there is no data in the database, a null value is returned. GetReference does not directly access the database. ??? Further in-depth understanding, GetReference throws an exception when the database record does not exist.

JPA is persistent in propagation. For operations performed on entities loaded using EntityManager instances, JPA tracks the changed entities and marks them as "dirty data ", this process is called "automatic dirty data check ". Operations completed on entities will lead to update statements. When a developer commits a transaction, JPA will execute these update statements. As long as the entity is connected to the EntityManager and the EntityManager remains open, the entity will be tracked. When EntityManager is disabled, the loaded entities are separated (the entities are in the Free State) and their state changes are not tracked. In this case, a new EntityManager instance needs to be reloaded or reassociated with the object using the merge operation.

 

The above is the JPA configuration and usage record. The next record uses Spring to use JPA for data access.

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.