POJO The object is actually our entity , This blog summarizes the framework for POJO Object corresponding database primary key generation strategy , And some of them POJO Simple operation of adding, deleting, modifying and querying objects .

  One ,Hibernate There are three ways to generate the primary key in the framework :

1, The database is responsible for generating the primary key ( surrogate key )

 a,native: It means that the set dialect determines which database is used to generate the primary key , for example : stay MySQL We're going to use a self-growing approach in our business , The primary key fields must all be integer types ; stay Oracle In the database , It's going to grow in a sequential way .

 b,sequence: It means to use the sequence of database to generate primary key , Apply to Oracle,DB2 In the database .

 c,identity: It means to use self growing primary key generation method , Apply to MySQL,SQL Server in .

2,Hibernate The framework is responsible for generating primary key values ( surrogate key ):

 a,increment: Indicates that the counter is provided by the framework itself , Accumulate data , Get primary key .

b,uuid: By the frame according to the parameters (IP Address ,JVM Virtual machine startup time , system time , Counter, etc ) Generate 32 position 16 A string of decimal digits .

3, The user provides the primary key value ( Naturally ):

Assigned: Business ( own ) Provide primary key .

Of course, it's often used here native,uuid and Assigned Ternary . Set up POJO When a class maps to a table , Set the primary key , The label is <id>, Among them <generator> Set in the tag , for example :

<!--
id Tags are used to map primary key fields
name Properties represent properties of a class
column Properties represent the fields of the table
-->
<id name="usercode" column="usercode" length="32" type="java.lang.String">
<!-- Primary key generation policy -->
<generator class="assigned"/>
</id>

Two ,Hibernate Under the framework of POJO Three states of an object :

 1, Instantaneous state ( Temporary state ):Transient Object

Object is not associated with the data in the database , And it's not associated with the framework . for example , We just  new User();

2, Persistent state :Persistent Object

Objects are associated with data in the database , And associated with the framework . For example, what we just saved  session.sava(user);

3, Free state ( Offline status , Hosting status )Detached Object

Objects are associated with data in the database , But it has nothing to do with frameworks . For example, after saving session closed user.

Look at three states POJO Object conversion :

  3、 ... and ,Hibernate, For the three states of POJO The operation of adding, deleting, modifying and checking :

Instantaneous state

Persistent state

Free state

increase (Save)

Sure

Can not be ( It is not necessary to )

Can not be ( It is not necessary to )

Change (Update)

Can not be

It will be updated automatically after modification , There's no need to manually

Sure

Delete (delete)

Can not be

Sure

Sure

check

Can not be

Sure

Sure

1, preservation (Save):

adopt session.save(user); You can save the data , But here I want to mention , The generation strategy of primary key is different , Frame sending sql The time of the statement is different :

a,native: Calling save Method insert sentence .

b,uuid Primary key generation strategy and assigned Primary key generation policy : Send... When a transaction is committed insert sentence .

This is because the primary key is generated at different times , because native It's generated in the database , So it was sent earlier .

2, to update (Update):

I want to talk about the update of free objects :

uuid

assigned

native

There are records

send out upate sentence

Will query and judge , Update again

send out update sentence

Record does not exist

Send statement , It's abnormal

Will query and judge , Insert operation

Send statement , It's abnormal

3, Delete (delete):

Here, just provide the primary key , According to the primary key id Delete , as long as id To exist is to .

4, Inquire about :

a, Primary key query :

get: The return result may be : Persistent objects or null, So we need to make a non null judgment on the result . It takes advantage of caching , It's an immediate inquiry .

//get Method query if successful , Then the returned object state is persistent state

Objectobj = session.get(User.class, "admin");

 load: The return result may be : Persistent objects or cglib Proxy object or exception , Using the cache , The default is delayed loading .

//load Method 1: store the query results in the cache , Supports delayed loading , More efficient , But mainly

Objectobj = session.load(User.class, "admin");

b, Common query ( Object oriented query ): We'll introduce

1,Query:

HQL (HibernateQuery Language),HQL Language is right SQL The encapsulation of language , It's an object-oriented query language . for example :SQL : select * from t_user( Table name ) where username( Field )="tom"

HQL : from User( Class name ) where username( attribute )="tom"

// Paging query 
String hql = "from User u "; // Object oriented query HQL!!!!!
Query query = session.createQuery(hql);
int pageno = 3 ;
int pagesize = 2 ;
int index = (pageno - 1) * pagesize ; query.setFirstResult(index);// The first subscript of a page
query.setMaxResults(pagesize); // The size of the number of pages // Conditions of the query
String hql = "from User u where u.usercode=? and u.userpswd=?"; // Object oriented query HQL!!!!!
Query query = session.createQuery(hql);
query.setString(0, "admin"); // Index from 0 Start
query.setString(1, "admin");

2,   Criteria: All operations will be done in an object-oriented way .

Criteria cra = session.createCriteria(User.class);
cra.setFirstResult(0); // Start index
cra.setMaxResults(2); // Number of pages // Sort
Criteria cra = session.createCriteria(User.class);
cra.addOrder(Order.desc("username")); // Conditions of the query
Criteria cra = session.createCriteria(User.class);
cra.add(Restrictions.eq("username", "aaa"));
cra.add(Restrictions.eq("usercode", "aaa"));
 

  In conclusion Hibernate Yes POJO Simple manipulation of objects , It's mainly about mapping , Simple configuration , And then use it Hibernate The method inside is configured . Here are a few simple examples, involving less knowledge , We can see Hibernate For reference , It will help us a lot !

Hibernate( Two )——POJO Object operation of more related articles

  1. Hibernate( Two ) Persistent object state

    brief introduction Previous studies Hibernate The notes , Sort it out and send it out , To prevent losing . If there is a mistake, please leave a comment , Be deeply grateful . The persistent classes Hibernate Complete the mapping from the object represented by the object-oriented model to the data structure represented by the relational model , ...

  2. ( Twelve )Hibernate Multiple table operations in (2): One way many to one

    from “ many ” We know that “ One ” Information about the party , For example, multiple employees use the same apartment , Employees can get information about the apartment , And apartments don't know about employees . Case a : Use xml To configure pojo class Group.java package bean; // ...

  3. Hibernate Three states ;query Inquire about ;ResultTransformer Convert to pojo object ; To be able to query Statement written in xml in ;Criteria Inquire about ;ProjectionList The sum of the /f Grouping and so on

    Copyright notice : This article is an original blog article , It can't be reproduced without the permission of the blogger . https://blog.csdn.net/u010026901/article/details/24256091 Session In the process of operation po ...

  4. Java One of the three frameworks ——Hibernate Association mapping and cascading operations

    What is? Hibernate Association mapping in ? Simply speaking Hibernate yes ORM Persistence layer framework for mapping , The full name is (Object Relational Mapping), Object relation mapping . It maps the tables in the database to the corresponding ...

  5. 【Hibernate frame 】 Three persistent states of objects

    One . review hibernate Objects in have three states , Namely TransientObjects( Instantaneous object ).PersistentObjects( Persistent object ) and DetachedObjects( Managed objects are also called offline ...

  6. 【hibernate Report errors 】No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 【get and load The difference between 】

    Report errors : HTTP Status 500 - Could not write content: No serializer found for class org.hibernate.proxy.poj ...

  7. Hibernate And Session Object related methods and persistent object state

    One . Persistent object state         From the perspective of persistence , Hibernate Divide the objects into 4 States : Persistent state , Temporary state , Free state , Delete status .Session A specific method of making an object transition from one state to another ...

  8. Hibernate( Four ) Object state and level 1 cache

    One .Hibernate Object state in 1.1. Instantaneous state ( Temporary state ) With no Hibernate Association There is no association with records in the database ( An association is a connection to a table in a database id Corresponding ) get : It's usually created directly (new) Instant ...

  9. No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer

    The exception information is as follows : com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for cla ...

Random recommendation

  1. From 202.97.60.193 icmp_seq=48 Time to live exceeded

    From a telecom company in Zhejiang ip On ping A certain Internet address outside the mainland doesn't work , Report the following information : From 202.97.60.193 icmp_seq=48 Time to live exceeded google, Baidu ...

  2. ningbo uber Uber driver registration course UBER Ningbo driver Registration Guide !

      since 2012 year Uber Since the beginning of the global March , Now it has entered the world 56 A market of countries and regions , More than 270 Cities provide services , and Uber The company's valuation has reached 412 Billion dollars . [ It's open now Uber Uber's car Hailing service in Chinese cities ] ...

  3. [ turn ]SharePoint All kinds of things that might be used in development Context( Context )

    SharePoint It's a B/S Structural products , So various contexts are used in the development process (Context) Information , Take this opportunity to summarize . especially Javascript Of Ctx Very practical , Here is a record of ! One .Http ...

  4. jQuery Ajax Operation function

    jQuery Ajax Operation function jQuery The library has complete Ajax Compatibility Suite . The functions and methods allow us to load data from the server without refreshing the browser . function describe jQuery.ajax() Asynchronous execution H ...

  5. Single case mode in Java and C# In the implementation of

    Singleton pattern is the most common and easy to understand design pattern . It usually means that only one instance of a class exists , I think the existing space can be understood as the application system in which the class is located , The other is to exist in a single container , Such as spring Of IOC Containers ( The scope is ...

  6. 5.toogleButton as well as Switch

    Switch Now it's used more , Than toogleButton Beautiful interface , The user experience is also better . Click event : use isChecked To determine which one to click on , And then respond accordingly .

  7. angular2 How to load on demand ?

    angular2 use webpack Packing is just a single package every time mian file , It's big , For example, on the page about us , Contact us on pages like this , Users may hardly open , But we still have to let the user load it every time , The experience is very bad , So we need to add ...

  8. discuz@ Function code

    // Reprint $atlist = $atlist_tmp = $ateduids = array(); preg_match_all("/@([^\r\n]*?)\s/i", $mes ...

  9. YYKit Note it FPS

    FPS computing method FPS yes Frame per second Abbreviation , The number of frames per second . The term is widely used in computer graphics , Video capture , Games etc. . CADisplayLink CADisplayLink It's a place where we can ...

  10. stay Visual Studio 2017 Configure and use OpenGL

    stay Visual Studio 2017 Configure and use OpenGL author : Kaluga Gio - Blog Garden  http://www.cnblogs.com/kailugaji/ First, in the Windows Lower installation Visual ...