Java Web series: Hibernate basics, webhibernate
Learn about hibernate ORM in the following five aspects.
(1) configuration file: hibernate. cfg. xml XML file and hibernate. properties attribute File
(2) object ing: 1-to-many, multiple-to-many
(3) Session factory and Session: SessionFactory & Session
(4) query: Native SQL query, General HQL query, and Criteria condition Query
(5) Transaction: Transanction
The five core objects Conifguration, SessionFactory, Session, Query, and Transanction of Hibernate must be mastered. In addition, there is no integration query similar to the language of Linq.
1. configuration file: hibernate. cfg. xml XML file and hibernate. properties attribute File
Hibernate uses Configuration to indicate the Configuration information. The Configuration file information is eventually adapted to the Configuration object. Although the XML file has been supported by hibernate, it is simpler to use the hibernate. properties attribute file.
The HSQLDB database is a common JAVA version of the test database. We use the following two methods to demonstrate the configuration of the HSQLDB database. Connection. driver_class, connection. url, connection. username, and connection. password provide the database connection information used by JDBC,Dialect configures the SQL dialect, and enables automatic update of the database mode in hbm2ddl. auto Configuration. show_ SQL and format_ SQL configurations allow us to view the output information on the console, and generate_statistics configurations generate statistics.
(1) Configure HSQLDB databases in XML format:
1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 6
(2) configuration file:
1 hibernate.connection.driver_class org.h2.Driver2 hibernate.connection.url jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE3 hibernate.connection.username sa4 hibernate.dialect org.hibernate.dialect.H2Dialect5 hibernate.hbm2ddl.auto update6 hibernate.show_sql true7 hibernate.format_sql true8 hibernate.generate_statistics true
2. Object ing: 1-to-many, multiple-to-many
Hibernate object ing can adopt XML and code annotations ,. the entity ing of EntityFramework in. NET also has the corresponding annotation (feature) method, but it provides a cleaner code configuration method for entity classes. Whether it is dependency injection or object ing, Spring and Hibernate are always relatively backward and cumbersome in this respect.
The core of various JAVA frameworks is never xml, and the core functions and objects of the framework are the most important. The core annotation of annotation configuration is as follows:
(1) @ Entity: The annotation class is an object.
(2) @ Id and @ GeneratedValue: the former indicates that the POJO field is the primary key, and the latter indicates that the field is automatically generated by the database.
(3) @ onetoworkflow and @ ManyToOne: Mark one-to-many and multiple-to-one pairs on the associated fields.
(4) @ manyto: Mark multiple-to-many pairs on the associated fields. The cascade parameter specifies cascading processing rules.
(5) @ Version: The annotation field is an optimistic concurrency control Version field.
The following describes the common one-to-many and many-to-many ing configurations.
(1)1-to-many: Category-Post
Category Code:
1 @Entity 2 public class Category { 3 4 @Id 5 @GeneratedValue 6 private int id; 7 8 private String Name; 9 10 @OneToMany11 private List<Post> posts = new ArrayList<Post>();12 13 public int getId() {14 return id;15 }16 17 public void setId(int id) {18 this.id = id;19 }20 21 public String getName() {22 return Name;23 }24 25 public void setName(String name) {26 Name = name;27 }28 29 public List<Post> getPosts() {30 return posts;31 }32 33 public void setPosts(List<Post> posts) {34 this.posts = posts;35 }36 }
Post Code:
@Entitypublic class Post { @Id @GeneratedValue private int id; private String Name; private String Text; @ManyToOne private Category category; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getText() { return Text; } public void setText(String text) { Text = text; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; }}
(2)Many-to-many + optimistic lock: User-Role
User code:
1 @Entity 2 public class User { 3 @Id 4 @GeneratedValue 5 private int id; 6 7 private String userName; 8 9 private String password;10 11 @Version12 private long version;13 14 @ManyToMany(cascade = CascadeType.ALL)15 private List<Role> roles = new ArrayList<Role>();16 17 public int getId() {18 return id;19 }20 21 public void setId(int id) {22 this.id = id;23 }24 25 public String getUserName() {26 return userName;27 }28 29 public void setUserName(String userName) {30 this.userName = userName;31 }32 33 public String getPassword() {34 return password;35 }36 37 public void setPassword(String password) {38 this.password = password;39 }40 41 public long getVersion() {42 return version;43 }44 45 public void setVersion(long version) {46 this.version = version;47 }48 49 public List<Role> getRoles() {50 return roles;51 }52 53 public void setRoles(List<Role> roles) {54 this.roles = roles;55 }56 57 }
Role code:
1 @Entity 2 public class Role { 3 @Id 4 @GeneratedValue 5 private int id; 6 7 private String roleName; 8 9 @ManyToMany(cascade = CascadeType.ALL)10 private List<User> users = new ArrayList<User>();11 12 public int getId() {13 return id;14 }15 16 public void setId(int id) {17 this.id = id;18 }19 20 public String getRoleName() {21 return roleName;22 }23 24 public void setRoleName(String roleName) {25 this.roleName = roleName;26 }27 28 public List<User> getUsers() {29 return users;30 }31 32 public void setUsers(List<User> users) {33 this.users = users;34 }35 }
3. Session factory and Session: SessionFactory & Session
(1) Session Context SessionFactory
SessionFactory is always the core object of Hibernate. SessionFactory created through Configuration is the core object of Hibernate ORM. Hibernate 4.3.5 and Hibernate 5.x can use the same code to create the SessionFactory, but jta (javax. transaction) needs to be introduced in 5.x; otherwise, the creation fails.
1 public SessionFactory sessionFactory() { 2 3 org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration(); 4 5 configuration.addAnnotatedClass(User.class); 6 configuration.addAnnotatedClass(Role.class); 7 configuration.addAnnotatedClass(Category.class); 8 configuration.addAnnotatedClass(Post.class); 9 10 SessionFactory sessionFactory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().build());11 return sessionFactory;12 13 }
(2) Session
The Session object is similar to the DbContext object in EntityFramework. In Hibernate, Session is obtained through SessionFactory. There are two methods: openSession () and getCurrentSession (). OpenSession to obtain a single open Session, you need to write your own code to close it. The getCurrentSession method can obtain automatically managed Session objects, which are supported by the Implementation class of the CurrentSessionContext interface. You can configure hibernate. current_session_context_class. The values "jta", "thread", and "managed" correspond to three implementation classes respectively. When using getCurrentSession, you do not need to manually manage the closing of the Session, but you need to manually manage the opening and closing of the Transaction. When Spring inherits from Hibernate, Spring provides the implementation class SpringJtaSessionContext of CurrentSessionContext, which avoids manual transaction management. In a Servlet environment without Spring, we can use the Filter + getSession method to use the Session. You can also set it to "thread" + manual transaction management.
Filter + getSession can directly use the Filter and SessionContext In the click-extras package. It is best to reuse and modify its source code, the core of SessionContext is to use static fields of ThreadLocal <Session> type to share sessions at the Thread level.
The pom of click-extras is as follows:
1 <dependency>2 <groupId>org.apache.click</groupId>3 <artifactId>click-extras</artifactId>4 <version>2.3.0</version>5 </dependency>
To use the "thread" + manual transaction management method, you must first configure the hibernate. properties attribute file: hibernate. current_session_context_class thread.
1 private void Test(SessionFactory factory)2 {3 factory.getCurrentSession().beginTransaction();4 Query query = factory.getCurrentSession().createSQLQuery("select * from User where userName=?").addEntity(User.class);5 User user = (User) query.uniqueResult();6 factory.getCurrentSession().getTransaction().commit();7 }4. Query: Native SQL query, General HQL query, and Criteria condition Query
(1) Native SQL query:
Native queries use the subinterface SQLQuery of the Query interface. You can use session to create instances for this interface. In the following code, the placeholder for hsqldb parameterized query is "? ". For ease of use, the addEntity method of SQLQuery is used to configure the object type of the query.
1 private User SqlQuery() {2 Session session = SessionContext.getSession();3 Query query = session.createSQLQuery("select * from User where userName=?").addEntity(User.class);4 query.setString(0, "admin");5 return (User) query.uniqueResult();6 }
(2) General HQL query:
Hibernate uses the Query interface to implement common queries through custom HQL. HQL provides an intermediate language that shields syntax differences between different databases. You can use session to create an instance of the Query interface.
1 private User SqlQuery() {2 Session session = SessionContext.getSession();3 Query query = session.createQuery("from User where userName=:userName");4 query.setString("userName", "admin");5 return (User) query.uniqueResult();6 }
(3) Criteria condition query:
Hibernate provides support for automatic query methods through the Criteria object. The secondary class Restrictions provides a large number of static methods to create the Criteria object. The biggest role is to prevent incorrect SQL keywords. Java does not provide integrated query in the same language as that in. NET.
1 private User CriteriaQuery() {2 Session session = SessionContext.getSession();3 Criteria query = session.createCriteria(User.class);4 query.add(Restrictions.eq("userName", "admin"));5 return (User) query.uniqueResult();6 }5. Transactions
The Transanction interface is an interface that encapsulates transactions in Hibernate. It supports JDBC database transactions and JTA distributed transactions. You can use the Session object to manage transactions. JAT transactions are closely related to the JTA container and will be resumed later.
1 private void Test(SessionFactory factory) {2 factory.getCurrentSession().beginTransaction();3 Query query = factory.getCurrentSession().createSQLQuery("select * from User where userName=?")4 .addEntity(User.class);5 User user = (User) query.uniqueResult();6 factory.getCurrentSession().getTransaction().commit();7 } Reference
(1) http://docs.jboss.org/hibernate/orm/5.0/quickstart/html/
(2) https://www.ibm.com/developerworks/cn/java/j-lo-jta/
(3) https://www.ibm.com/developerworks/cn/java/j-lo-hibernate3/