JPA Study Notes-Hello world

Source: Internet
Author: User

JPA Study Notes-Hello world
* Java Persistence API: API for Object Persistence * Java EE 5.0 standard ORM specification, so that applications can access the persistence layer in a unified way. JPA is an abstraction of hibernate (like the relationship between JDBC and JDBC drivers):-JPA is a specification: JPA is essentially an ORM specification, not An ORM framework-Because JPA does not provide ORM implementation, it only develops some specifications and provides some programming API interfaces, but the specific implementation is provided by the ORM vendor-Hibernate is implementation: in addition to the ORM framework, Hibernate is also a JPA implementation. In terms of functions, JPA is a subset of Hibernate functions. One of the goals of JPA is to develop an API that can be implemented by many vendors, currently, Hibernate 3.2 +, TopLink10.1 +, and OpenJPA provide the Implementation of JPA. Hibernate is the author of Hibernate-since 3.2 compatible with JPAOpenJPA-OpenJPA is an open-source project provided by the Apache organization. TopLink-TopLink was previously charged, and now the advantages of JPA are standardized: the same API is provided, which ensures that enterprise applications developed based on JPA can run under different JPA frameworks after a few modifications. Easy to use and easy to integrate: One of the main goals of JPA is to provide a simpler programming model. Creating entities in the JPA framework is as simple as creating Java classes. You only need to use javax. persistence. entity annotation; JPA's framework and interfaces are also very simple, comparable to JDBC's query capability: JPA's query language is object-oriented, and JPA defines a unique JPQL, it also supports batch update and modification, JOIN, group by, HAVING, and other advanced query features that can only be provided by SQL, and even subqueries. Supports advanced object-oriented features: JPA supports advanced object-oriented features, such as inheritance between classes, polymorphism, and complex relationships between classes, to maximize the use of object-oriented model JPA includes three technical ORM ing metadata: JPA supports XML and JDK 5.0 annotations, metadata describes the ing between an object and a table. The framework then persists the object to a database table. JPA APIs: These APIs are used to operate entity objects and perform CRUD operations. The framework completes all things in the background and developers are freed from tedious JDBC and SQL code. Query Language (JPQL): This is an important aspect in persistent operations. It queries data through object-oriented rather than database-oriented query languages to avoid close coupling between programs and specific SQL statements. The project directory structure wkiom1ywsqxdz6m4aabmrdrwvla224.jpg lib needs to add the Hibernate required directory, jar under the jpa directory, and MySQL driver. 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"> <! -- Configure what ORM product to use as JPA Implementation 1. the actual configuration is javx. persistance. spi. implementation class of PersistanceProvider interface 2. if there is only one JPA implementation product in the JPA project, you can also choose not to configure this node --> <provider> org. hibernate. ejb. hibernatePersistence </provider> <! -- Add a persistence class --> <class> com. jpa. beans. customer </class> <properties> <property name = "javax. persistence. jdbc. driver "value =" com. mysql. jdbc. driver "/> <property name =" javax. persistence. jdbc. url "value =" jdbc: mysql: // test "/> <property name =" javax. persistence. jdbc. user "value =" root "/> <property name =" javax. persistence. jdbc. password "value =" "/> <! -- Configure the basic attributes of JPA to implement the product, that is, the basic attributes of Hibernate --> <property name = "hibernate. format_ SQL "value =" true "/> <property name =" hibernate. show_ SQL "value =" true "/> <property name =" hibernate. hbm2ddl. auto "value =" update "/> </properties> </persistence-unit> </persistence>

 

Customer. java entity class
@ Table (name = "jpa_customer") @ Entitypublic class Customer {@ Column (name = "id") @ GeneratedValue (strategy = GenerationType. AUTO) @ Id private Integer id; @ Column (name = "last_name") private String lastName; private String email; private int age; // omit getter stter}

 

Main. java
Public class Main {public static void main (String [] args) {// 1. create EntityManagerFactory String persistenceUnitName = "Jpa"; // persistence. entityManagerFactory entityManagerFactory = persistence. createEntityManagerFactory (persistenceUnitName); // 2. create EntityManager entityManager = entityManagerFactory. createEntityManager (); // 3. enable the transaction EntityTransaction entityTransaction = entityManager. getTransaction (); entityTransaction. begin (); // 3. persistent operation Customer customer = new Customer (); customer. setAge (22); customer. setEmail ("[email protected]"); customer. setLastName ("Shang"); entityManager. persist (customer); // 5. commit the transaction entityTransaction. commit (); // 6. disable EntityManager entityManager. close (); // 7. disable EntityManagerFactory entityManagerFactory. close ();}}

 

The JPA basic annotation @ Entity indicates that the Java class is an Entity class and will be mapped to the specified database table before it is used for object class declaration statements. For example, if you declare an object class Customer, it maps to the customer table in the database. @ Table when the object class is different from the database Table name mapped to it, the @ Table annotation must be used in parallel with the @ Entity annotation before the object class declaration statement, it can be written in a separate statement line or in the same way as the declaration statement. The common option for @ Table annotation is name, which indicates the Table name of the database. @ Table annotation also has two options: catalog and schema, which are used to set the database directory or mode to which the Table belongs, usually the database name. The uniqueConstraints option is used to set constraints, which are usually not required. @ Id annotation is used to declare that the attributes of an object class are mapped to the primary key column of the database. This attribute is usually placed before the attribute declaration statement. It can be the same as the declaration statement or written in a separate row. @ Id annotation can also be placed before the property's getter method. @ GeneratedValue is used to mark the generation policy of the primary key, which is specified through the strategy attribute. By default, JPA automatically selects a primary key generation policy most suitable for the underlying database: SqlServer corresponds to identity and MySQL corresponds to auto increment. In javax. persistence. generationType defines the following policies to choose from:-IDENTITY: the database ID increases automatically from the primary key field, which is not supported by Oracle;-AUTO: JPA automatically selects an appropriate policy, which is the default option.-SEQUENCE: generates a primary key through the SEQUENCE, and specifies the SEQUENCE name through @ SequenceGenerator annotation. MySql does not support this method.-TABLE: generates a primary key through the TABLE, the framework generates a primary key using a table simulation sequence. This policy makes it easier for applications to port databases. @ Basic indicates the ing of a simple attribute to fields in the database table. For the getXxxx () method without any annotation, the default value is @ Basicfetch, which indicates the read policy of this attribute, there are two types: EAGER and LAZY, which respectively indicate master node crawling and delayed loading. The default value is EAGER. optional: whether the attribute is allowed to be null. The default value is true @ Column. When the attribute of an object is different from the Column name of the database table mapped to it, the @ Column annotation is required, this attribute is usually placed before the attribute declaration statement of the object and can be used with the @ Id annotation. The common attribute of @ Column annotation is name, which is used to set the name of the Column mapped to the database table. The annotation also contains multiple other attributes, such as unique, nullable, and length. @ ColumnDefinition attribute marked by Column: indicates the actual type of the field in the database. generally, the ORM framework can automatically determine the type of fields in the database based on the attribute type, but the Date type still cannot determine whether the field type in the database is DATE, TIME or TIMESTAMP. in addition, the default ing type of String is VARCHAR. If you want to map the String type to the BLOB or TEXT field type of a specific database. @ Column annotation can also be placed before the getter method of the attribute. @ Transient indicates that this attribute is not a ing of fields to the database table. The ORM framework ignores this attribute. if an attribute is not a field ing of a database table, you must mark it as @ Transient. Otherwise, by default, the orm framework annotation is @ Basic @ Temporal. In the core Java API, the precision of the Date type is not defined (temporal precision ). in the database, data of the Date type has three precision types: DATE, TIME, and TIMESTAMP (that is, simply Date, TIME, or both ). you can use the @ Temporal annotation to adjust the precision of property ing.

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.