A prelude to Hibernate
After so long, I finally had time to learn about Hibernate. The configuration was complicated.
In the development process, layers are often seen, mainly for decoupling.
B/S is divided into three layers at least:
View presentation layer
Action/sevlet/xx data
Jsp Template
Service Layer
Dao data access layer
The following is a real start to Hibernate.
First, import some necessary jar packages. The database uses MySQL, and the database driver package is required to connect to the database.
Project directory:
The Project created for debugging is a Java Project.
Entity class User. java
package test.hibernate.domain;public class User {private int id;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn [User:id=+id+,name:+name+];}}The configuration file hibernate. cfg. xml. The file name is hibernate. cfg.
Org. hibernate. dialect. MySQLDialect
Com. mysql. jdbc. Driver
Jdbc: mysql: // localhost: 3306/hibernate_2015
Root
686175
True
User. hbm. xml
The value of the class attribute of id is native, indicating that the configuration attribute in the database is used.
Main test class App. java
Package test. hibernate. domain; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import org. hibernate. classic. session; import org. junit. test; public class App {private static SessionFactory sessionFactory; static {Configuration cfg = new Configuration (); cfg. configure (hibernate. cfg. xml); sessionFactory = cfg. buildSessionFactory () ;}@ Testpublic void testSave () throws Exception {User user = new User (); user. setName (James); Session session = sessionFactory. openSession (); Transaction transaction = session. beginTransaction (); session. save (user); transaction. commit (); session. close (); // close the session and release the resource} @ Testpublic void testGet () throws Exception {Session session = sessionFactory. openSession (); Transaction transaction = session. beginTransaction (); User user User = (User) session. get (User. class, 1); System. out. println (user); transaction. commit (); session. close ();}}