preface

ORM frameworks are not a new topic, they have been with us for years. It provides a conceptual, easy-to-understand data model that maps tables in the database to objects in memory. There are two ORM frameworks commonly used in Java: Hibernate and iBatis. This article focuses on using Hibernate and will follow in iBatis.

Traditional MVC development pattern

  1. M: the ModelincludingPojo, Service, DAO.
  2. V: the ViewincludingJSP, HTML, module engine.
  3. C: ControllincludingOur technology for dynamic Web resources: Servlets.

The role of the SSH framework in development

  • S: Struts/for SpringMVC:In fact, it solves the problem of our controller (simply think of it as Servlet encapsulation).
  • Spring:To integrate the rest of the third-party frameworks is toSrviceLayer provides transactions.
  • Hibernate:This is the DAO layer solution.

Meanwhile, we can take a look at the meanings of other frameworks (SSM and SSS) :

What is the Hibernate

Hibernate is a non-invasive ORMapping framework

Non-invasive framework: We use this framework without inheriting or implementing the classes or interfaces in the framework. This type of framework is called non-invasive framework, and the non-invasive framework is better decoupled from the original framework when used

Intrusive frameworks: When we use a framework, we need to inherit or implement certain classes or interfaces from the framework

ORMapping parsing

O: Object

R: a function

M: Mapping Mapping

  1. Hibernate has the ability to map Java objects to databases through mapped relationships

  2. Hibernate can map database data to Java objects through mapping relationships

Hibernate is a technology that can manipulate a database by manipulating Java objects.

What Hibernate can do

Simply put: Implementation of database All Operations (CRUD) is a solution to the original DAO layer, but also a replacement.

Simple use of Hibernate

“Simple use:”

  • Package guide, put the downloaded required+ JPA related packages into a file
  • Create the hibernate.cfg.xml configuration file under SRC
<? The XML version = '1.0' encoding = "utf-8"? > <! DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" > < hibernate configuration - > < session - factory > <! - Driver - > < property name = "hibernate. Connection. Driver_class" > com. Mysql.. JDBC Driver < / property > <! <property name="hibernate.connection. URL "> JDBC :mysql:///qianyu</property> <! - username - > < property name = "hibernate. Connection. The username" > root < / property > <! - password - > < property name = "hibernate. Connection. Password" > root < / property > <! The dialect tells the Hibernate framework which SQL statement you are currently generating for the database name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <! <property name=" hibernate.hbm2dcl. auto">update</property> <! - configuration mapping file - > < mapping resource = "com/qy/helloworld/User. HBM. XML" / > < / session - factory > < / hibernate - configuration >Copy the code
  • Create Java class object
public class User implements Serializable{ private static final long serialVersionUID = -6949433888868762441L; private int uId; private String userName; private String userPwd; public User(int uId, String userName, String userPwd) { super(); this.uId = uId; this.userName = userName; this.userPwd = userPwd; } public User() { super(); } public int getuId() { return uId; } public void setuId(int uId) { this.uId = uId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } @Override public String toString() { return "User [uId=" + uId + ", userName=" + userName + ", userPwd=" + userPwd + "]"; }}Copy the code
  • Writing test classes
@test public void testHelloWord() throws Exception {// Imports the Configuration file. Configuration CFG =new Configuration().configure("hibernate.cfg.xml"); SessionFactory sf= cfg.buildsessionFactory (); Session =sf.openSession(); // Start transaction session.beginTransaction(); User User =new User(1," Koba ","110"); Session.save (user); // Commit the transaction session.getTransaction().commit(); session.close(); }Copy the code
  • Hibernate Hibernate. Cfg. XML configuration file in detail
<? The XML version = '1.0' encoding = "utf-8"? > <! DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" > < hibernate configuration - > <! --> <session-factory> <! <property name="connection.driver_class"> com.mysql.jdbc.driver </property> <! <property name="connection. URL "> JDBC :mysql:// qianyu</property> <! <property name="connection.username">root</property> <! Password --> <property name="connection.password">root</property> <! - dialect is told Hibernate framework to generate the database you are currently under the SQL statements -- > < property name = "the dialect" > org. Hibernate. The dialect. MySQL5Dialect < / property > <! Update: create a new table each time --> <! <property name=" hbm2dcl. auto">update</property> <! <property name="show_sql">true</property> <! <property name=" format_SQL ">true</property> <! - configuration mapping file configuration is mapping file - > < mapping resource = "com/qy/helloworld/User. HBM. XML" / > <! -- Use this one when using annotations --> <! -- <mapping package="com.qy.helloworld"/> --> </session-factory> </hibernate-configuration>Copy the code
  • Hibernate xxx.hbm. XML configuration file in detail
<? The XML version = "1.0"? > <! DOCTYPE hibernate-mapping PUBLIC "-// hibernate /Hibernate Mapping DTD 3.0//EN" "Http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" > <! Auto-import ="true": if not, you must write the full path of the class when performing queries --> <! - the default - lazy: <hibernate-mapping package="com.qy.helloworld" default-lazy="true" auto-import="true"> <! Mysql > select * from JAVA class where table = 'name'; mysql > select * from JAVA class where table = 'name'; mysql > select * from JAVA class where table = 'name' Class name="User" table="t_user" lazy="true"> <! -- id: indicates the mapping of the primary key name: indicates the name of the primary key in the class column: indicates the field of the table corresponding to the primary key length: determines the maximum length of the current field Type: Type (write the full path of data types in JAVA) Note: Type can be omitted: the omitted type is the same as the type in the entity. Length: can be omitted. The default is the maximum range of int. Column: This can also be omitted name="uId"> <! -- Self-growth for primary key -- Select self-growth policy assigned based on the underlying database foreign: Use someone else's primary key as your own primary key Increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment increment --> <generator class="identity"/> </id> <! Type: type --> <property name="userName" column="userName" length="20" column="userName" length="20" not-null="true"/> <property name="userPwd" length="20" not-null="true" type="java.lang.String"/> </class> </hibernate-mapping>Copy the code
  • Implementation of CRUD in Hibernate
Add data session.save(user); session.persist(user); Modify data session.beginTransaction(); User User =session.get(user.class,1); User.setusername (" XXXXX "); user.setUserPwd("yyyyy"); session.getTransaction().commit(); User User =session.get(user.class,1); User2 =session.load(user.class,1); User User =session.get(user.class,1); session.delete(user);Copy the code
  • Hibernate help class preparation
public class HibernateUtils { private static Configuration cfg=null; private static SessionFactory sf=null; private static ThreadLocal<Session> threadLocal=null; ThreadLocal =new threadLocal <Session>(); CFG =new Configuration(). Configure ("config/hibernate.cfg.xml"); // generate our factory sf= cfg.buildsessionFactory (); } @title: getSession * @description: TODO * @param: @return * @return: Session * @throws */ public static Session getSession(){ Session session=threadLocal.get(); if(null==session){ session=sf.openSession(); session.beginTransaction(); threadLocal.set(session); } return session; } /** * close Session * @title: close * @description: TODO * @param: * @return: void * @throws */ public static void close(){ Session session=threadLocal.get(); if(null! =session){ session.getTransaction().commit(); session.close(); threadLocal.remove(); }}}Copy the code

Matters needing attention

  1. Our hibernate.cfg. XML configuration file contains this brackethibernate.Yes can be omitted
  2. Why can data be queried without enabling transactions? becauseHibernate has read-only transactions by defaultRead-only transactions can complete the operation of reading data. If you want to complete the operation of adding, deleting and modifying data, then you need to read and write transactions. At this time you need to enable transactions

Difference between Save and Persist

  • When saving data, if the ID is self-increasing, you are right to give an ID or not to give an ID.
  • Persist will cause an error if you give an ID that grows automatically when saving data.

conclusion

This is the end of the introduction to Hibernate, there will be more Hibernate series of more articles, thank you for your support!