Hibernate (1)--data Access Layer Architecture mode < turn >

Source: Internet
Author: User
Tags event listener

    • Concept, logic and data model concept of database
    • Tiered architecture development for applications
    • The corresponding relationship between MVC design pattern and four-layer structure
    • Design goals for the persistence layer
    • Data Mapper Schema Mode
    • Disadvantages of JDBC
    • About Hibernate
    • Quick use of Hibernate development examples
    • Hibernate's core classes and interfaces, and their relationships
    • Comparison of Pojo and JavaBean
A summary of the previous article: Database Essence Knowledge Point Summary (1)-The database of three-tier mode and two-level image, E-R (Entity contact map) diagram, the relational model is simply, in the field of software development, you can use models to represent real-world entities. The database is divided into:
    • Conceptual model (Analysis phase): Generally does not describe the behavior of the entity, both technical and non-technical staff can read.
    • Logical model (Design phase)
    • Physical model/data model (Implementation phase)

Example computer;

In the requirements analysis phase, we have to consider the computer concept model: brand, color, price ... In the design phase, you need to build a logical model, such as building an entity class (including properties and methods), in the physical model phase, we want to save the entity to the database, we need to establish a table ... Insert the data into the table, and the attributes of the entity correspond to the fields of the table. Their relationship is as follows:

Naturally, developers need to link data models (relational) and domain models (object-oriented), since the mainstream databases are relational databases, such as common mysql,oracle,sqlserver ... and our program (most of the time) is an object-oriented model.

  PS: Relational databases store data in rows and columns for easy user understanding. This series of rows and columns is called a table, and a set of tables makes up a database. The table has a relationship to the data record between the tables. The relationship model is essentially a two-dimensional table.

    • Table-------Entities
    • Field-------Properties
    • Record--------Instances
    • View
    • Index
    • Primary key, primary key satisfies three points feature: 1. Uniqueness, 2. Non-null, 3. Not modifiable
      • There is also a primary key called the proxy primary key: does not have a business logic meaning. Like MySQL's auto_increament, uniqueidentify.
    • Triggers/stored Procedures

  

  The following is a simple look at the association between entities and entities:

    • One-to-one, such as a citizen corresponding to an ID number
    • One to many (a pair of many), such as a citizen with multiple bank card accounts
    • Many to many (many-to-many), such as a teacher corresponding to multiple students, while a student corresponding to a number of teachers

  

  The completeness of a simple review table

    • Entity integrity (uniqueness of table records, resolved by primary key)
    • Referential integrity (consistency of master table data)
    • Domain integrity (type and constraint checking)
    • User-defined integrity (user-defined constraints), for example: Exam score 0-100 is reasonable and requires user-defined

  Tiered architecture development for applications

There is a top-down dependency between layers and layers, where the upper component accesses the API for the underlying component, and the lower component should not rely on the upper component. For example, the presentation layer relies on the business logic layer, and the business logic layer relies on the database layer, each layer exposes the API to the upper level, but the specific implementation details are transparent to the outside. When the implementation of a layer changes, as long as its API does not change, it will not affect the implementation of the other layers. Benefits of software tiering:
    • Scalability: Scalability refers to whether the application can support more users
    • Maintainability: Maintainability refers to the need to modify a portion of the software, without affecting the code of the other part, when changes in demand occur
    • Extensibility: Scalability refers to the ease with which new features are added to existing systems. The more layers, the extension points can be provided in each layer without breaking the overall framework of the application
    • Reusability: reusability means that the program code is not redundant and the same program can meet a variety of requirements. For example, the business logic layer can be shared by multiple presentation tiers
    • Manageability: Manageability refers to the ease of managing a system. When you divide your application into tiers, you can break it down to different development teams for easy management

The following is a review of the data mapper schema pattern:

The relationship between objects in a program is different from a table in a relational database, a table of a database can be thought of as a grid of rows and columns, and a row in a table can be associated with a row in a foreign key and another table (or even the same table), and the object's relationship is complex: An object may contain other objects, Different data structures may organize the same objects in different ways ... object and relational data are two representations of business entities, and business entities behave as objects in memory and behave as relational data in the database.

To relate the data itself in the relational database to the memory object that handles the business logic, you can associate the two with the data mapper. A data mapper is a layer of intermediate software that separates memory objects from the database and moves data between them, keeping objects and databases (and the mapper itself) separate from each other. In a nutshell, a data mapper is a class of data that maps data to objects, which is responsible for transforming data between objects and relational databases, effectively hiding database operations in the domain model and managing unavoidable conflicts in database transformations.

The most powerful part of the data Mapper architecture pattern is the elimination of coupling between domain layers and database operations. The data mapper works behind the scenes and can be applied to a variety of object-relational mappings. The result is the need to create a large number of specific mapper classes, but now the mainstream web development framework can be automatically generated and maintained ... For example, the Hibernate framework, which mentions object-relational mappings, continues to summarize:

  Object-Relational mapping (object/relation Mapping, short ORM)

is a result of the development of object-oriented software development methods. The object-oriented development method is the mainstream development method in the enterprise application development environment, and the relational database is the mainstream data storage system which is stored permanently in the enterprise-level application environment. The essence of it is to represent the business data in the relational data (library) in the form of objects, and to organize these objects by object-oriented (object-oriented) way, and realize the process of the system business logic.

First look at the background, Javaweb development, the server side is usually divided into the presentation layer, the business layer, the persistence layer, this is the so-called three-tier architecture:

    • 1, the presentation layer is responsible for receiving user requests, forwarding requests, display data, etc.;
    • 2, the business layer is responsible for organizing business logic;
    • 3, the persistence layer is responsible for persisting the business object, essentially encapsulates the data access details, provides the object-oriented API for the business logic layer, so that the business layer can focus on implementing the business logic ("persistence" includes various operations related to database, save, UPDATE, delete, load, query);

Each of these three tiers has a different pattern, the schema pattern, such as.

  

The corresponding relationship between MVC design pattern and four-layer structure

  

   design goals for the persistence layer
    • Code reusability is high, and object persistence can be accomplished
    • Ability to support multiple database platforms, if needed
    • Have relative independence, when the persistence layer changes, does not affect the upper layer implementation

Previously, we were using the Java JDBC API directly for database operations.

Disadvantages of JDBC programming :

    • Business logic and relational data binding, if the relational data model changes, such as modifying the structure of the table, then you must manually modify all the relevant SQL statements in the program code, increasing the difficulty of software maintenance
    • Embedding relational-oriented SQL statements in program code so that developers cannot fully use object-oriented thinking to write programs
    • If the SQL statement in your program code contains syntax errors, you cannot check for this error at compile time, which can be found at run time, which increases the difficulty of the debugger

While the architecture pattern of the persistent layer is commonly used in the Data Mapper architecture pattern,hibernate is an implementation of the data Mapper architecture pattern, hibernate (Bear) hibernation, it is a persistent layer of open-source framework, solve the problem of object-relational mapping, Relatively large, but also very intelligent (relative ibatis, this ibatis is very simple, follow-up and incidentally summarized).

    • Hibernate is an encapsulation of the JDBC API, a JDBC Lightweight package framework that enhances code reuse, simplifies code, and improves programming efficiency
    • So that Java programmers can easily use object-oriented programming ideas to manipulate the relational database.
    • Because hibernate is a lightweight package for JDBC, Java programmers can easily bypass hibernate to access the JDBC API directly, if necessary.
    • Hibernate can be applied not only in standalone Java programs, but also in Java Web projects, can be integrated with multiple Web servers, and supports a variety of database platforms

Looking at the graph, hibernate is implemented as a data Mapper architecture pattern in the third layer of the Web development three-tier architecture-the data persistence layer.

Hibernate supports very, very many database systems by persisting the code (data) in the business logic into the data source (relational database) through Hibernate (data persistence layer). The following small try sledgehammer, write a Hibernate application demo. Simply create a Java application. The jar package that needs to be referenced: The Core jar package is: Hibernate3.jar, all of the following:

There is also a jar package for the MySQL database connection.

  The general steps for writing hibernate applications are no more than the following 4 steps:

    • Create Hibernate profile: Hibernate needs to read the database configuration information from the configuration file, typically located in the project root path. Hibernate configuration file in two different ways.
      • Hibernate.properties (key = value mode)
      • Hibernate.cfg.xml (must be in src root directory)
    • Create a persisted class Xxx.java: A class whose instance needs to be persisted by hibernate into the database, that is, the entity class
    • Create an object for a persisted class-relational map file: Xxx.hbn.xml, which must be placed in the package corresponding to the entity class
    • Write code to access the database through the Hibernate API to persist objects

So easy!

  For the configuration file, we can go to the jar package example to find, see the official example, or a random online search a bunch of ... There is no need to remember!!! The key is the mastery of ideas and principles.

Hibernate configuration file is a typical XML file, we only keep the Session factory section, the contents of the content do not.

<! DOCTYPE hibernate-configuration public    "-//hibernate/hibernate configuration DTD 3.0//en"    "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">

Create a database BBS, a table user

The persistence class and the table of our database have correspondence, so the premise is that there must be a database table user two-dimensional table (at least 1) and the corresponding entity class user class, I am in the VO package (the object of the data object: The value of the page and the value of the transfer between page objects) established:

View Code

At the same time it is also a Pojo class--pojo full name is Plain ordinary Java object/plain old Java Object, Chinese can be translated into: Ordinary Java class, with a part getter/ The class of the setter method can be called the Pojo class.

The XML file that creates the object-relational map must be placed in the corresponding package for the entity class (My is Vo) and the name strictly corresponds to: class name. hbm.xml

View Code

The <class> element is used to specify a mapping between a class and a table, the Name property sets the class name (including the path), the table property is set to the name, and the default is the class name

The ID child element sets the oid of the persisted class and the table's primary key mapping, and the child element of the ID < generator> element specifies the generator of the OID. Property child elements set the properties of the class and the mapping of the table's fields
    • name– the property name of the corresponding class
    • type– the type of the specified property
    • column– Specifies the name of a table field
    • not-null– Specifies whether the property is allowed to be empty

Add Hibernate's main profile hibernate.cfg.xml (need to be placed in the SRC root directory), and don't forget to introduce the previous object-relational mapping profile into the master profile, mapping ...

View Code

Create a DAO package and write code to access the database through the Hibernate API, where you must know some of the core classes and interfaces of hibernate. As follows:

  The core classes and interfaces of the Hibernate framework

  1. sessionfactory: is a core interface , equivalent to hibernate and a database connection of a large butler, it caches hibernate configuration information and mapped metadata information, belongs to the heavyweight, So the instantiation of its implementation class only need to be instantiated once, and can not be easily closed, if closed, and the database is disconnected, in addition, the connection of different databases, the need to establish a different sessionfactory object, and instantiate the class, you need to use an implementation of the interface class-- Configures a class configuration to create an instance of a session after it is instantiated with the object of the configuration.
      1. Creation of the Sessionfactory, Configuartion.buildsessionfactory ().
      2. sessionfactory is thread-safe and can be safely shared by multiple threads, typically with only one sessionfactory instance for the entire application.
      3. Sessionfactory Cache
        1. Built-in cache, storing hibernate configuration information and mapping metadata information, physical media is memory
        2. External cache, is a configurable cache plug-in, can hold a large number of copies of database data, physical media can be memory or hard disk
  2. Configuration: is the implementation class of the Sessionfactory interface .
    1. The implementation of the class two features
      1. Responsible for managing hibernate's underlying configuration information, including: Database URL, database username and password, JDBC driver, database dialect, database connection pool, etc.
      2. Generates a Sessionfactory object that creates a Sessionfactory object that can create a session
    2. The two methods used
      1. Property file (hibernate.properties), calling code: Configuration cfg = new configuration ();
      2. XML file (hibernate.cfg.xml), calling code: Configuration cfg = new configuration (). Configure ();
  3. Session: Also an interface, inherited sessionfactory,session is the basic core of Hibernate persistent operation, can be easily understood as the connection object in the previous JDBC.
      1. Session creation (dependent on sessionfactory, Sessionfactory object from Configuartion.buildsessionfactory (); Configuartion This instantiation object comes from the new Configuration (). Configure ();), Session session = Sessionfactory.opensession (); Represents a database connection, with the session connection, the database can be manipulated (crud), it is called the session is the persistence manager. And the operation of the database, we need to encapsulate into the transaction, that is, Hibernate's transaction
      2. The session is a lightweight object that is non-thread-safe and typically binds to a database transaction.
  4. Transaction: An interface that abstracts application code from the underlying transaction implementation, which is a JDBC transaction or a JTA transaction that can be specified in the configuration file, which is the JDBC transaction by default.
      1. Calling code: Transaction tx = Session.begintransaction ();
      2. When working with Hibernate, you must explicitly call transaction (default: Autocommit=false)

Class Diagram:

  

A second introduction to the query and Criteria interface

The query interface, which allows the programmer to execute queries on the database and control how the query executes, the query statement uses the SQL of Hibernate's HQL or local database, calling code: Query query = Session.createquery ("from User");

The criteria interface is an object representation of traditional SQL, calling code: Criteria = Session.createcriteria (Tuser.class);

  

Structure

The code is as follows:

View Code

    

The entire project structure

The running result is correct, the data is inserted successfully; Hibernate:insert into user (username, password, userId) VALUES (?,?,?)

2016-02-02 23:22:30,202 | INFO  | main | dashuai.dao.UserDao.main (userdao.java:47)                                                            | transaction.commit (); ok2016-02-02 23:22:30,207 | INFO  | main | dashuai.dao.UserDao.main (userdao.java:57)                                                            | session.close (); ok

  Summary: Mappings for persistence classes and relational databases

  Tell me the difference between Pojo and JavaBean?

In the first place, what Pojo is--The ordinary Java class, the class that has a part of the Getter/setter method can be called Pojo, ideally, a pojo is a Java object that is not subject to any restrictions (except the Java language Specification). For example a pojo should not be

    1. Extending a predetermined class
    2. Implementing a predetermined interface
    3. Contains predefined annotations, such as @javax. Ejb.entity public class baz{...

But JavaBean is much more complex than Pojo, JavaBean is a reusable component, JavaBean does not have a strict specification, in theory, any Java class can be a Bean. In general, however, because JavaBean is created by a container (such as Tomcat), JavaBean should have an parameterless constructor, and generally JavaBean implement the Serializable interface to implement Bean persistence. JavaBean cannot be accessed across processes.

  So why do you need JavaBean?

Because Java lacks attributes, events, and multiple inheritance capabilities. So in Java to implement some of the common requirements of object-oriented programming, only a large number of handwritten glue code. JavaBean is the customary pattern or convention for writing this set of glue code. The simplest understanding of it is the packet, which contains information (attributes), such as name, gender, and other methods (get and set methods) that can assign and value these attributes. By instantiating the assignment, you can take the value out of the Get method elsewhere. This is JavaBean, or VO. If you have some logic in the method, such as getname, you need to prefix name with the company name ... Usually, it's called Bo. and the database table corresponding to the persistence class is generally called Pojo, these things can be collectively referred to as JavaBean, the core is the assignment (set) and the value (get). If you need to use a read-write disk cache, network transmission is required ... You need to serialize the JavaBean. Implement the Serializable interface.

The spring in Action book says in detail:

  JavaBean: is a public Java class, but for editing tool recognition, at least three conditions need to be met:

    1. There is a public default constructor (for example, no parameter constructor)
    2. The Get,set property is accessed using the public's method, which means that the property is set to private, and the size of the Get,set method and the property name need to correspond. For example, the attribute Name,get method will be written, public String getName () {},n uppercase.
    3. Serialization is required. This is the framework, tools cross-platform to reflect the state must be
    4. Overriding the Hashcode and Equals methods (optional) ...

......

Here's a break.EJBThe concept of:
    • In the year of java1996 release, December that was published in the Java bean1.00-a, what is the use of it? This allows Java objects to be reused and uniformly manipulated, such as the original AWT component (for example, a dot point (x, y), the IDE can automatically show its state volume x, y to configure ,). This is the origin of JavaBean,
    • In the actual enterprise development, need to realize the transaction, the security, the distributed, the JavaBean is not good to use. Sun began to heap functions, piled up into a reinforced version of the JavaBean, which is the origin of the EJB;
    • EJB is powerful, but it's too heavy, and many times it's overkill! At this point, the programming technology has progressed, that is Di (dependency injection), AOP (face-to-surface), developers can now through the very simple JavaBean can also complete the EJB thing.
    • Spring was born.
In general, in enterprise development, the need for scalable performance and transaction, security mechanism, so as to ensure the smooth development of enterprise systems, rather than the development of a scale to replace a set of software systems. And then you raise the protocol requirements, and there's aEnterprise Bean. EJB has made some demands on the basis of JavaBean, which is of course more complicated.POJO:There is a call Josh Mackenzie people think, EJB is too complex, there is no need to use every time, so invented a pojo,pojo is ordinary javabean, what is ordinary, and EJB corresponding.    In short, the difference is that you first determine whether to meet the conditions of JavaBean, and then if the implementation of some requirements, the EJB is satisfied with the condition of the EJB, otherwise it is pojo. "Think in Java" in the last chapter of the GUI said: JavaBean originally for the Java GUI implementation of visual programming, drag IDE build tool to create a GUI component (such as multi-box) is actually a tool for you to create a Java class, and exposes the properties of the class to you to modify the adjustment, exposing the event listener.

"Www.cnblogs.com/kubixuesheng/p/5177238.html"

Hibernate (1)--data Access Layer Architecture mode < turn >

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.