Spring learning 2 combination of spring and Hibernate
Spring + hibernate routine --
In this article, the spring + hibernate routine is just made from the simplest combination, and does not involve more specific or complex content. After all, for spring or hibernate alone, every one of them is not just a few words, and the principle is simple. However, once the application is involved, all aspects of consideration and the content to be processed will be much changed. Besides, the framework itself has a relatively large API, however, this requires continuous use to become more skillful.
The software development process in this article is as follows:
- Investigate and analyze requirements, and establish modules and entities
- Design table Structures Based on entities to create tables in the database
- Obtain the class from the data table and construct the ing file.
- Write and process business logic through the framework
Some tools can generate source files with XDoclet tags and generate HBM files through XDoclet. In this example, the relevant management of Hibernate is directly sent to spring, so there is no separate configuration file for hibernate. This article believes that general applications are sufficient. Of course, if it is complicated, you need to conduct in-depth research and learning on each framework.
This routine assumes that the table structure has been determined, and the process from the table to the class and from the class to the ing file is only a set of code, however, the following will focus on the process from table to class, including the XDoclet tag, and hope to have corresponding open-source and free tools available.
Environment:
- Eclipse 3.2
- For MySQL 4.1
The procedure is as follows:
1. Download spring and hibernate. The download file is as follows:
- Spring-framework-2.0.1-with-dependencies.zip
Http://www.springframework.org
- Hibernate-3.2.2.ga.zip
Http://www.hibernate.org/
And decompress the package to any location, just to help you find the corresponding package for use.
2. The list of related packages used in this example is as follows, which can be found from the above two packages.
- Antlr-2.7.6.jar
- Aopalliance. Jar
- ASM. Jar
- Cglib-2.1.3.jar
- Commons-collections.jar
- Commons-dbcp.jar
- Commons-logging.jar
- Commons-pool.jar
- Dom4j-1.6.1.jar
- Hibernate3.jar
- JTA. Jar
- Mysql-connector-java-3.1.12-bin.jar
- Spring-aop.jar
- Spring-beans.jar
- Spring-context.jar
- Spring-core.jar
- Spring-dao.jar
- Spring-hibernate3.jar
- Spring-jdbc.jar
3. Create a data table. In this example, only two simple tables are used to demonstrate a new operation. The two tables are tbl_customer and tbl_account. The constructed SQL statements are as follows:
Drop table if exists 'tbl _ customer ';
Drop table if exists 'tbl _ account ';
Create Table 'tbl _ customer '(
'Customer _ id' int (11) unsigned not null auto_increment,
'Customer _ email 'varchar (82) not null default '',
'Customer _ password' varchar (10) Not null default '',
'Customer _ userid' varchar (12) not null default '',
'Customer _ firstname 'varchar (25) not null default '',
'Customer _ lastname 'varchar (25) not null default '',
Primary Key ('customer _ id '),
Unique key 'customer _ userid' ('customer _ userid ')
) Type = MyISAM;
Create Table 'tbl _ account '(
'Account _ id' int (11) unsigned not null auto_increment,
'Customer _ id' int (11) not null default '0 ',
'Account _ name' varchar (50) not null default '',
'Account _ type' varchar (20) not null default '',
'Create _ date' date not null default '2017-00-00 ',
'Update _ date' date not null default '2017-00-00 ',
'Account _ balance 'Double (15, 3) not null default '0. 000 ',
Primary Key ('account _ id ')
) Type = MyISAM;
4. construct related account and customer classes as follows (Note: Here, NO content is added to XDoclet because this routine was created earlier than the XDoclet routine, and there is no good solution from table to class ):
Customer. Java
Package net. ofbase. hibernate. example;
Import java. Math. bigdecimal;
Import java. util. hashset;
Import java. util. Set;
Public Class Customer {
Private long id = new long (-1 );
Private string userid;
Private string password;
Private string email;
Private string firstname;
Private string lastname;
Private bigdecimal balance;
Private set accounts = new hashset ();
Public String getemail () {return email ;}
Public void setemail (string email) {This. Email = Email ;}
Public String GetPassword () {return password ;}
Public void setpassword (string password) {This. Password = password ;}
Public long GETID () {return ID ;}
Public void setid (long ID) {This. ID = ID ;}
Public set getaccounts () {return accounts ;}
Public void setaccounts (set accounts) {This. Accounts = accounts ;}
Public void addaccount (account Account ){
Account. setcustomer (this );
Accounts. Add (account );
}
Public bigdecimal getbalance () {return balance ;}
Public void setbalance (bigdecimal balance) {This. Balance = balance ;}
Public String getfirstname () {return firstname ;}
Public void setfirstname (string firstname) {This. firstname = firstname ;}
Public String getlastname () {return lastname ;}
Public void setlastname (string lastname) {This. lastname = lastname ;}
Public String getuserid () {return userid ;}
Public void setuserid (string userid) {This. userid = userid ;}
}
Account. Java
Package net. ofbase. hibernate. example;
Import java. util. date;
Public class account {
Private long id = new long (-1 );
Private string accountname;
Private string type;
Private double balance;
Private date createdate;
Private date updatedate;
Private customer;
Public String getaccountname () {return accountname ;}
Public void setaccountname (string accountname) {This. accountname = accountname ;}
Public date getcreatedate () {return createdate ;}
Public void setcreatedate (date createdate) {This. createdate = createdate ;}
Public long GETID () {return ID ;}
Public void setid (long ID) {This. ID = ID ;}
Public String GetType () {return type ;}
Public void settype (string type) {This. type = type ;}
Public date getupdatedate () {return updatedate ;}
Public void setupdatedate (date updatedate) {This. updatedate = updatedate ;}
Public customer getcustomer () {return customer ;}
Public void setcustomer (customer) {This. Customer = Customer ;}
Public double getbalance () {return balance ;}
Public void setbalance (double balance) {This. Balance = balance ;}
}
5. Two HBM files.
Customer. HBM. xml
<? XML version = "1.0" encoding = "GBK"?>
<! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en"
Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>
<Hibernate-mapping>
<Class name = "net. ofbase. hibernate. example. Customer"
Table = "tbl_customer" dynamic-update = "false" dynamic-insert = "false">
<ID name = "ID" column = "customer_id" type = "Java. Lang. Long"
Unsaved-value = "-1">
<Generator class = "native"/>
</ID>
<Set name = "accounts" inverse = "true"
Cascade = "all-delete-Orphan">
<Key column = "customer_id"/>
<One-to-learn class = "net. ofbase. hibernate. example. Account"/>
</Set>
<Property name = "email" type = "string" update = "false"
Insert = "true" column = "customer_email" length = "82" not-null = "true"/>
<Property name = "password" type = "string" update = "false"
Insert = "true" column = "customer_password" length = "10" not-null = "true"/>
<Property name = "userid" type = "string" update = "false"
Insert = "true" column = "customer_userid" length = "12" not-null = "true"
Unique = "true"/>
<Property name = "firstname" type = "string" update = "false"
Insert = "true" column = "customer_firstname" length = "25"
Not-null = "true"/>
<Property name = "lastname" type = "string" update = "false"
Insert = "true" column = "customer_lastname" length = "25" not-null = "true"/>
</Class>
</Hibernate-mapping>
Account. HBM. xml
<? XML version = "1.0" encoding = "GBK"?>
<! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en"
Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>
<Hibernate-mapping>
<Class name = "net. ofbase. hibernate. example. Account" table = "tbl_account"
Dynamic-update = "false" dynamic-insert = "false">
<ID name = "ID" column = "account_id" type = "Java. Lang. Long"
Unsaved-value = "-1">
<Generator class = "native"/>
</ID>
<Role-to-one name = "customer" column = "customer_id"
Class = "net. ofbase. hibernate. example. Customer" not-null = "true"/>
<Property name = "accountname" type = "string" update = "false"
Insert = "true" column = "account_name" length = "50" not-null = "true"/>
<Property name = "type" type = "string" update = "false" insert = "true"
Column = "account_type" length = "1" not-null = "true"/>
<Property name = "createdate" type = "date" update = "false"
Insert = "true" column = "create_date" not-null = "true"/>
<Property name = "updatedate" type = "date" update = "true"
Insert = "true" not-null = "true" column = "update_date"/>
<Property name = "balance" type = "double" update = "true"
Insert = "true" column = "account_balance" not-null = "true"/>
</Class>
</Hibernate-mapping>
6. Spring configuration file spring-hibernate-bean.xml.
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype beans public "-// spring // DTD bean // en"
Http://www.springframework.org/dtd/spring-beans.dtd>
<Beans>
<Bean id = "ds"
Class = "org. springframework. JDBC. datasource. drivermanagerdatasource">
<Property name = "driverclassname">
<Value> com. MySQL. JDBC. Driver </value>
</Property>
<Property name = "url">
<Value>
JDBC: mysql: // localhost/test? Useunicode = true & amp; characterencoding = gb2312
</Value>
</Property>
<Property name = "username">
<Value> root </value>
</Property>
<Property name = "password">
<Value> Maude </value>
</Property>
</Bean>
<! -- Hibernate sessionfactory, defined to pass to the class that inherits hibernatedaosupport -->
<Bean id = "hibernatesessionfactory"
Class = "org. springframework. Orm. hibernate3.localsessionfactorybean">
<Property name = "datasource">
<Ref local = "ds"/>
</Property>
<Property name = "hibernateproperties">
<Props>
<Prop key = "hibernate. dialect">
Org. hibernate. dialect. mysqldialect
</Prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
</Props>
</Property>
<! -- Here you need to include all the O-R ing files -->
<Property name = "mappingresources">
<List>
<Value> customer. HBM. xml </value>
<Value> account. HBM. xml </value>
</List>
</Property>
</Bean>
<! -- Pass session factory to userdao -->
<Bean id = "mermerdaotarget"
Class = "net. ofbase. hibernate. example. impl. customerdaoimpl">
<Property name = "sessionfactory">
<Ref local = "hibernatesessionfactory"/>
</Property>
</Bean>
<Bean id = "TM"
Class = "org. springframework. Orm. hibernate3.hibernatetransactionmanager">
<Property name = "sessionfactory">
<Ref bean = "hibernatesessionfactory"/>
</Property>
</Bean>
<Bean id = "userdao"
Class = "org. springframework. transaction. Interceptor. transactionproxyfactorybean">
<Property name = "transactionmanager">
<Ref local = "TM"/>
</Property>
<Property name = "target">
<Ref local = "customerdaotarget"/>
</Property>
<Property name = "transactionattributes">
<Props>
<Prop key = "addcustomer"> propagation_required </prop>
</Props>
</Property>
</Bean>
</Beans>
7. Create the DaO interface.
Accountdao. Java
Package net. ofbase. hibernate. example;
Public interface accountdao {
Public abstract void addaccount (account Account );
}
Customerdao. Java
Package net. ofbase. hibernate. example;
Public interface customerdao {
Public abstract void addcustomer (customer );
Public abstract customer getcustomeraccountinfo (customer );
}
8. implement these two Dao interfaces for data operations.
Customerdaoimpl. Java
Package net. ofbase. hibernate. example. impl;
Import java. util. List;
Import net. ofbase. hibernate. example. customer;
Import net. ofbase. hibernate. example. customerdao;
Import org. springframework. Orm. hibernate3.support. hibernatedaosupport;
Public class customerdaoimpl extends hibernatedaosupport implements customerdao {
/** Save the instance */
Public void addcustomer (customer) {gethibernatetemplate (). Save (customer );}
Public customer getcustomeraccountinfo (customer ){
Customer Cust = NULL;
List list = gethibernatetemplate (). Find (
"From customer where customer. userid =? ", Customer. getuserid ());
If (list. Size ()> 0)
Cust = (customer) list. Get (0 );
Return Cust;
}
}
Accountdaoimpl. Java
Package net. ofbase. hibernate. example. impl;
Import net. ofbase. hibernate. example. Account;
Import net. ofbase. hibernate. example. accountdao;
Import org. springframework. Orm. hibernate3.support. hibernatedaosupport;
Public class accountdaoimpl extends hibernatedaosupport implements accountdao {
Public void addaccount (account Account) {gethibernatetemplate (). Save (account );}
}
9. Create the Test Program Main. java.
Package net. ofbase. hibernate. example;
Import java. util. date;
Import net. ofbase. hibernate. example. impl. customerdaoimpl;
Import org. springframework. Context. Support. classpathxmlapplicationcontext;
Import org. springframework. Orm. hibernate3.localsessionfactorybean;
Public class main {
Public static classpathxmlapplicationcontext appcontext = NULL;
Public static void main (string [] ARGs ){
Try {
// Obtain the spring Context
Classpathxmlapplicationcontext appcontext =
New classpathxmlapplicationcontext (
New String [] {"spring-hibernate-bean.xml "});
// Instantiate the customer
Customer customer = new customer ();
Customer. setemail ("base.x@126.com ");
Customer. setuserid ("base ");
Customer. setpassword ("123456 ");
Customer. setfirstname ("base ");
Customer. setlastname ("xia ");
// Instantiate an account
Account ACC = new account ();
ACC. setaccountname ("base ");
ACC. settype ("C ");
ACC. setcreatedate (new date ());
ACC. setupdatedate (new date ());
ACC. setbalance (New Double (500.00 ));
// There is an association here
Customer. addaccount (ACC );
// Create a DaO instance and add a one-to-Multiple Association
Customerdaoimpl =
(Customerdaoimpl) appcontext. getbean ("customerdaotarget ");
Customerdaoimpl. addcustomer (customer );
// Retrieve the stored value from the database
Customer o = customerdaoimpl. getcustomeraccountinfo (customer );
System. Out. println ("find the customer, and its user id value is" + O. getuserid ());
} Catch (exception e ){
E. printstacktrace ();
}
}
Private Static void createdatabaseschema () throws exception {
Localsessionfactorybean sessionfactory = (localsessionfactorybean) appcontext
. Getbean ("& frameworksessionfactory ");
Sessionfactory. dropdatabaseschema ();
Sessionfactory. createdatabaseschema ();
}
}
10. Run main. Java and get the following prompt:
......
Hibernate: insert into tbl_customer (customer_email, customer_password, customer_userid, customer_firstname, customer_lastname) values (?, ?, ?, ?, ?)
Hibernate: insert into tbl_account (customer_id, account_name, account_type, create_date, update_date, account_balance) values (?, ?, ?, ?, ?, ?)
Hibernate: Select customer0 _. customer_id as customer1_0 _, customer0 _. customer_email as customer2_0 _, customer0 _. customer_password as customer3_0 _, customer0 _. customer_userid as customer4_0 _, customer0 _. customer_firstname as customer5_0 _, customer0 _. customer_lastname as customer6_0 _ from tbl_customer customer0 _ Where customer0 _. customer_userid =?
Find the customer whose user ID is base
11. Check the database. There is data in it.
The business logic in this example is very simple. You need to refer to some relevant materials in actual use. However, the spring and hibernate documents are still comprehensive, in addition, the development manuals and the like are already in the Chinese version, so you don't have to worry about e-paper.