You can create your own user Library. (Episode II)
Join the MySQL driver mysql-connector
Create the appropriate content in the database:
Create DATABASE hibernate;
Use hibernate;
CREATE TABLE student (ID int primary key, name varchar (), age int);
Establish the Student class:
To create a hibernate profile, Hibernate.cfg.xml:
<?xml version= ' 1.0 ' encoding= ' utf-8 '?>
<! DOCTYPE hibernate-configuration Public
"-//hibernate/hibernate Configuration DTD 3.0//en"
"Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<session-factory>
<!--database connection settings (hibernate automatically links you to databases, fills in relevant information)--
<property name= "Connection.driver_class" >com.mysql.jdbc.Driver</property>
<property name= "Connection.url" >jdbc:mysql://localhost/hibernate</property>
<property name= "Connection.username" >root</property>
<property name= "Connection.password" >abc123</property>
<!--JDBC Connection pool (use the built-in) (Hibernate connection pool)--
<!--<property name= "Connection.pool_size" >1</property>-
<!--SQL dialect (Hibernate dialect, hibernate unifies the SQL language, translates the unified language into the appropriate database language as written below)-
<property name= "dialect" >org.hibernate.dialect.MySQLDialect</property>
<!--Enable Hibernate ' s automatic session context management--
<property name= "Current_session_context_class" >thread</property>
<!--Disable the Second-level cache (two-level cache Disable off)-
<property name= "Cache.provider_class" >org.hibernate.cache.NoCacheProvider</property>
<!--Echo all executed SQL to stdout (prints the generated SQL statement)--
<property name= "Show_sql" >true</property>
<!--Drop and re-create the database schema on startup (whether to let hibernate automatically generate DDL (build table statements))--
<!--<property name= "Hbm2ddl.auto" >update</property>-
<mapping resource= "Com/bjsxt/hibernate/model/student.hbm.xml"/>
</session-factory>
Also specify the correspondence between the object and the table field. To create a mapping file, Studnet.hbm.xml:
<?xml version= "1.0"?>
<! DOCTYPE hibernate-mapping Public
"-//hibernate/hibernate Mapping DTD 3.0//en"
"Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<class name= "Student" >//find the corresponding class
<id name= "id" column= "id"/>//id represents the primary key
<property name= "Name"/>//property represents a generic field
<property name= "Age"/>
</class>
Write Test class:
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration;
Import com.bjsxt.hibernate.model.Student;
public class Studenttest {
public static void Main (String args[]) {
Student s = new Student ();
S.setid (1);
S.setname ("S1");
S.setage (1);
Configuration cfg = new configuration ();
Sessionfactory SF = Cfg.configure (). Buildsessionfactory ();//sessionfactory Produce Connecyion factory
Session session = Sf.opensession ();
Session.begintransaction ();
Session.save (s);//Insert object s into the database
Session.gettransaction (). commit ();
Session.close ();
Sf.close ();
}
}
annotation (using annotation annotations can be used without *.hbm.xml files):
To create a new table:
CREATE TABLE teacher (ID int primary key,name varchar (TEN), title varchar (20));
Set up object teacher and add annotation annotation:
Package Com.bjsxt.hibernate.model;
Import javax.persistence.Entity;
Import Javax.persistence.Id;
@Entity//Represents an entity class that corresponds to a table in a database table
public class Teacher {//annotation annotations can be used without *.hbm.xml files
private int id;
private String name;
Private String title;
@Id//Indicates primary key
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;
}
Public String GetTitle () {
return title;
}
public void Settitle (String title) {
This.title = title;
}
}
JDBC Operations database is cumbersome
SQL statements are relationship-oriented rather than object-oriented
You can create relationships between objects and relational tables to simplify becoming
O/R mapping spanning database platform
Table name is configured when the table name differs from the class name
Annotation: @Table
Xml:...
When the field name is the same as the property: The default is @basic;xml does not write column
When the field name differs from the property name:
Annotation: @Column
Xml:...
Fields that do not require psersitence (persisted, stored in the database):
Annotation: @Transient
XML: Do not write directly
Mapping date and time types, specifying time accuracy:
Annotation: @Temporal
XML: Setting the type attribute of the property label
mappings for enum types:
Annotation: @Enumerated
Xml:...
Location of annotations:
Can be placed above the field (member variable),
can also be placed above the GetXXX method.
JUNIT4 BUG: 19th video
ID generation policy: corresponding project hibernate_0400_id
Attention:
We observe that the structure of hibernate tables is not built for future use (and may also have their own extensions, such as index), but rather to understand what table and entity class mappings We should try to do.
XML Generation ID:
Using generator
There are four commonly used: native identity sequence UUID
Annotation Generate ID:
@GeneratedValue
There are four ways to take value: Auto identity sequence (@SequenseGenrator) table (@TableGenerator)
Federated PRIMARY Key:
Xml:composite-id (to implement serializable and override Equals and Hashcode)
Annotation
Annotate the class as @idclass and annotate all properties belonging to the primary key in the class entity as @id
Annotate the component class as @embeddable. And annotate the properties of the component as @id
Annotate the properties of a build as @embeddable
Hibernate's core development interface:
Sessionfactory has two ways to get the session:
1.openSession: Open a new session each time, run out to close
2.getCurrentSession: Get the current context (you can set current-context-class in the configuration file, mostly with JTA and thread) or open a new session ( After the previous session is commit), run out without closing, commit () and then automatically close.
The session is an interface, the two methods get the specific class may be different, so can not be mixed with
The difference between the two methods is very important
The difference is in the 26th episode.
JPA defines the boundaries of things, such as data depositing and logging, which need to be done within the same thing.
There is also a kind of thing JTA, distributed database.
Three states of the object:
How to differentiate:
1. Object has no ID
2.ID there is no in the database
3. There is no ID in memory (session cache)
1.transient: An object in memory, no ID, and no ID in the cache
2.persistent: ID in memory, ID in cache, database with ID
3.detached: Memory has ID, cache does not have ID, database has ID
Delete method:
You can call the Delete method whenever you have an ID
The difference between get and load:
Get will execute SQL statement to get object immediately
Load generates and returns a proxy object until you take the object's properties, and the agent executes the SQL statement to get the object
There is a difference when there is no corresponding record.
Update
Used with new detached object, can be converted to persistent state after update is completed
Update transient will error
The transient object that sets the ID to the new one (provided the database has a corresponding record)
When a field of a persistent object is changed, commit checks for changes and changes all fields.
The following method only lets him modify the corresponding modified field: the 32nd video.
Clear
Either load or get, the cache is searched first, and if not, the database lookup is made, and the call uses the Clear method to force clear the session buffer.
Flush
Synchronization from memory to the database can be enforced, and flush is performed once on commit.
Relational mappings:
The relationships between objects:
One:
Unidirectional:
Each husband corresponds to a wife,wife in which there is no corresponding Husbus, then this is a one-way association
In a database with a foreign key association
@OneToOne @JoinColumn (name= "Wifeid")
Bidirectional:
Each husband corresponds to a husbus in one wife,wife, this is a bidirectional association
@OneToOne (Mappedby)
Federated PRIMARY Key:
@JoinColums
One-to-many (multi-pair):
Tricksters Library table Design: Add foreign keys in more than one side.
Many-to-many:
One-Way Association:
The teacher needs to know which students he teaches, the relationship between teachers and students.
Bidirectional Association:
The teacher knows which students he teaches, and the students know what teachers they teach.
Also can be based on one-way or bidirectional can not be 7 kinds.
ctrl+alt+ copy this line to the next line
ALT + Move this line to the next line
PowerDesigner can be used to parse the code and generate a diagram of the table.
CRUD in an association relationship:
Set Cascade to set the action for the object when persisted.
C--create
R--retrieve (remove load get)
U--update
D--delete
Cascade Property The associated object is tied together when the action is fatal.
Merge=save+update
Refresh=a, we need to read the data after B's changed.
Iron Law: Two-way relationship in the program to set two-way relationship, two-way relationship set Mappedby (on the one side of the set)
Fetch
Two-way do not set eager on both sides (there will be redundant query statements issued)
For more than the party B set fetch time to be cautious, combined with the specific situation, a bunch of lazy use eager (special case: The number of multi-parties is not a lot of time can be considered, improve efficiency when you can consider).
O/rmapping Programming Model:
1. Mapping Models
Jap annotation
Hibernate annotation Extension
Hibernate xml
JAP XML
2. Programming interface
Jap
Hibernate
3. Data query:
Hql
EJBQL (JPQL)
To delete or update, load first, except for the exact ID number.
If you want to eliminate the association relationship, set it to null first, delete the record, and if you do not delete the record, the record becomes junk data. The 51st episode.
If a property fetch of @onetoone is specified as Fetchtype.lazy, the loading of the associated object is deferred, regardless of whether the load or get is used.
Relationship Mapping Summary: What kind of relationship, what kind of table to design, what kind of mapping.
Inheritance mappings:
1. A table single_table
2. One table for each class Table_pre_class
3. One table per subclass joined
Design of the tree structure (essential):
Use One2many and Many2one in a class.
Hibernate queries (Query language)
Hql&ejbql
1.NativeSQL
2.HQL (Hibernate QL)
3.EJBQL (JPQL 1.0)--can be considered as a subset of HQL
4.qbc
5.qbe
Performance optimization:
Note the use of session.clear (), especially in the continuous paging cycle, otherwise it will cause a memory leak.
Is there a memory leak in Java?
There is no syntax level, but in fact may be indirectly caused if he calls with C, in the Call OS, and C requires manual control of memory.
1+n problem (very important):
64th Episode
Solution:
1. Set the lazy
2.BatchSize
3.join Fetch
The most used is 1 3.
The difference between list and iterate:
1.list Take All
2.iterate first go to ID, and so on when used to come to the object by ID
3.session in the second issue of the list, will still go to the database query
4.iterate the second time, the session cache will be searched first
There are three kinds of caches in hiberbate:
1. First level cache (Session level)
2. Level two cache (Sessionfactory level)
Can exist across a session
A level two cache is used in the following situations:
1. Often accessed
2. Do not change frequently
3. Limited quantity
such as: User rights, organizational structure
Hibernate.cfg.xml settings:
<property name= "Cache.use_second_level_cache" >true</property>//open Level two cache
<property name= "Cache.provider_class" >org.hibernate.cache.encacheprovider</property>//indicates which level of two cache is used
Add Annotations:
@Cache
Load uses level two cache by default, and iterate uses level two cache by default
The list defaults to the level two cache plus data, but the query is not used by default
3. Query caching
Valid only if the query statement is exactly the same. The query cache relies on a level two cache, so a level two cache must be turned on at the same time.
Call the Setcachable (true) method of query to indicate that a level two cache is used.
Cache algorithm: (What to do when the cache is full)
1.lru:least recently Used (least recently used cleared)
2.lfu:least frequently Used (with the least frequency of removal)
3.fifo:first in first out (first to be cleared)
You can set which one to use in Ehcache:
Memorystoreevictionpolicy= "LRU"
Things are handled concurrently:
The nature of Things: ACID
Atomic (atomicity) Consistency (Independence) itegrity (consistency) durability (persistence)
Problems that often arise in things:
Dirty read non-repeatable read Phantom read
The isolation mechanism of things in the database:
1:read-uncommitted
2:read-committed
4:repeatable Read
8:serilizable
As long as the database supports things, it is impossible to have the first category lost and new.
Read-uncommitted will appear dirty Read,phanton-read,non repeatable read problem.
Read-committed does not appear dirty read, because only another thing submitted will read the result, but will still appear phanton-read,non repeatable read.
REPEATABLE read.
Serial solve all problems.
Set the object isolation level for hibernate:
General Settings hibernate.connection.isolation=2//consider efficiency
Solving the problem of repeatable read with pessimists (database-dependent locks)