1.ibatis Basic Knowledge
Semi-automated Java Persistence Layer Framework, open source free, core or JDBC, just encapsulate it, reduce the writing of repetitive code (according to some idle foreigner statistics, reduced by 62% of the Code), more in line with the object-oriented principle of coding.
-----------
|-What is persistence layer:----First say lasting: persistence is to save the data to a power-off storage device for subsequent use. (Saved from memory to disk, solidified)--done through a relational database.
----Persistence layer: At the logical level of the system, focus on a relatively independent field of data persistence. "Layer" indicates that there should be a relatively independent logical level, rather than "module/unit", there should be a clearer and stricter logical boundary.
————
|______ What is semi-automatic: Because Ibatis also wants programmers to write their own SQL statements to access the database. ------{Improved controllability, but SQL in the Ibatis configuration file changes as the database design changes. }
The characteristics of 2.ibatis
Advantages:
1 simple, the configuration file has only two jar packages: one is the jar package for the ibatis itself, and one is the jar package that connects the database
2) Separation of concerns: using Ibatis to deal with objects, there will be no scattered result sets
3 Portable: Portable, can be Java,ruby, #c平台上使用
Disadvantages:
1) can only be used on relational databases
2) SQL requires programmer writing. If the database design changes, you need to change the Ibatis configuration file, a bit cumbersome.
3. Example explanation Ibatis
First configure the Ibatis Jar Pack (two, I'm using Ibatis-2.3.4.726.jar and Mysql-connector-java-5.0.4-bin.jar)
Engineering documents as shown:
Java files:
User:pojo, is a persistent layer object, is also the object of Ibatis direct manipulation
Userdao: Pass the parameter (User) to the user.xml.
Configuration files include
Properties file for JDBC Connection: sqlmap.properties.
Ibatis General configuration file Sqlmapconfig.xml
The mapping file for each entity, which is the mapping file for the user class. User.xml Here the programmer writes SQL statements manually
The connection to the database is defined in Sqlmap.properties:
The key value pairs of the resource file that is key and value
Driver=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/tt
username=root
password=
General configuration file: Note-I added the JDBC data source directly to the general configuration file and didn't use the sqlmap.properties in the project.
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE sqlmapconfig public
"-//ibatis.apache.org//dtd SQL Map Config 2.0//en"
"Http://ibatis.apache.org/dtd /sql-map-config-2.dtd ">
<sqlMapConfig>
<!--defines a Ibatis transaction manager with 3 (jdbc,jta,external)-->
<transactionmanager type= the "JDBC" commitrequired= "false" >
<!--Type property specifies the type of link for the data source, and there are 3 types (simple, Dbcp,jndi)-->
<datasource type= "simple" >
<property name= "JDBC. Driver "value=" Com.mysql.jdbc.Driver "/>
<property name=" jdbc. Connectionurl "value=" Jdbc:mysql://localhost:3306/tt "/>
<property name=" jdbc. Username "value=" root "/>
<property name=" JDBC. Password "value=" "/>
</dataSource>
</transactionManager>
<!--configuration mapping file-->
<sqlmap resource= "Com/tt/user.xml"/>
</sqlMapConfig>
Explain:
About Ibatis transaction manager and Data source: http://blog.csdn.net/not_a_baby/article/details/6756943,
If the reference is Sqlmap.properties, the following:
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE sqlmapconfig Public "-//ibatis.com//dtd SQL Map Config 2.0//en"
"http://www.ibatis.com/dtd/ Sql-map-config-2.dtd ">
<sqlMapConfig>
<properties resource=" Com/tt/sqlmap.properties "/>
<transactionmanager type= "jdbc" >
<datasource type= "simple" >
<property name= "jdbc. Driver "value=" ${driver} "/>
<property name=" JDBC. Connectionurl "value=" ${url} "/>
<property name=" JDBC. Username "value=" ${username} "/>
<property name=" JDBC. Password "value=" ${password} "/>
</dataSource>
</transactionManager>
<sqlmap Resource= "Com/tt/user.xml"/>
</sqlMapConfig>
User's mapping file: "Check the user's additions and deletions I only implemented the increase and change as an example"
Here are the examples of sqlmap.xml that can often be seen ~ This part of code writing occupies about 70% of ibatis development.
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE sqlmap Public "-//ibatis.com//dtd SQL Map 2.0//en" "HTTP://WWW.IBATIS.COM/DTD/SQL-MAP-2.DTD" > &
lt;sqlmap> <select id= "Selectuser" parameterclass= "int" resultclass= "Com.tt.User" >
</select> <insert id= "Insertuser" parameterclass= "Com.tt.User" > <! [cdata[ Insert into user (name, age,sex, location) VALUES (
#name: varchar#, #age: int#, #sex: varchar#, # location:varchar# )]]> <selectkey resultclass= "int" keyproperty= "id" > select last_insert_id () as ID </selectKey> </insert> <deletE id= "DeleteUser" parameterclass= "int" > </delete> <select id= " Selectusers "parameterclass=" Com.tt.User "> </select> <update id=" UpdateUser "parameterclass=" Com.tt.User "> update User <dynamic prepend= "Set" > < Isnotnull prepend= "," property= "name" > name = #name: varchar# </isNotNull> <isnotnull prepend= "," property= "Sex" > sex = #sex: varchar# </ isnotnull> <isnotnull prepend= "," property= "Location" > location = #location: varchar# & nbsp; </isNotNull> <isnotnull prepend= "," property= "age" > age = #age # </isNotNull> </dynamic> where id = #id # &NBSP;&NBsp
</update> </sqlMap>
Explain:
Ibatis Mapping:
1) About primary keys:
Ibatis supports the gradual automatic generation of databases, including the pre-generated primary key (which is known as the primary key eg:oracle before the data is inserted) and the epigenetic Cheng (knowing who is the primary key after inserting the data, eg:mysql)
The generated primary key is set to the property of the same name-----The Keyproperty property specifies the primary key property
The position of the Selectkey is either a pre-generated primary key or a epigenetic primary key
2 If the SQL statement contains a > or < number (which may be available in the Where condition), use the <! [cdata[*********]]> to contain. Represents the included SQL statement, or it can contain only one > or < symbol
3 SQL Input Parameters Parameterclass
Insert statement into parameter: Parameterclass = ' Package. Class '
Query Statement entry: can be set to class name, map, or string,int, long, and so on. Only one soundtrack type (String,int,long) is used as an entry, and can be referenced using #value#.
For example:
<select id = "Selectuser" Parameterclass = ' long ' ResultClass = ' com.tt.User ' >
select * from User where id = #valu e#
</select>
In my case, there is no ID. These are examples of usage,
4) return value parameter type
ResultClass = ' Com.tt.User '-when the result set column name and the class attribute name exactly correspond, use the ResultClass
Resultmap = ' xxx '; ---when some columns do not correspond. Resultmap is a pojo mapping that requires the mapping of XML before it can be used.
For example:
<resultmap id= "Mapuser" class= "Com.tt.mapUser" >
<result property= "name" column= "name"/>
< Result property= ' age ' column= ' age '/>
</resultMap>
You need to create a Pojo class corresponding to the COM.TT package, the attribute member is name, age. Only the columns that you want to know
5 references to parameters in SQL
There are three ways to refer to Parameterclass:
1. Native type--int, string, long---using #value# #value # is not a keyword, variable
2. Map type parameters, use #keyname# to refer to, KeyName for health name
3. Object parameters, using #propertyname# to use the name of the object's properties. For example, the above name = #name # and so on.
6 references to parameters in fuzzy queries
Understand the difference between # # and $$.
#xxxx # is to pass XXXX as a parameter
$xxxx $ is to stitch the xxxx whole directly onto the SQL statement
In the vague query is, to----"% $Name $% '
7 The bright spot of dynamic SQL--ibatis
Prepend represents the link keyword, can be any string, when the SQL keyword is, ibatis Ono to determine whether to add the keyword.
8) Result set mapping inheritance
Inheritance is the reuse of the mapping definition.
For example
<resultmap id= "Baseuser" class= "Com.tt.User" >
<result property= "name" column= "name"/>
< Result property= ' age ' column= ' age '/>
</resultMap> <resultmap id= ' User2 ' class= ' Com.tt.User '
extends= "Com.tt.User.baseUser" >
<result property= "sex" column = "Sex"/>
</resultMap>
9 Ibatis Paging Query---"to be perfected"
SQL injection---"to be perfected"
One) Ibatis can configure caching
Ibatis the names of various IDs
The name of the interface name SQL Statement ID in the DAO layer is consistent,
User.java-Note that the property name should correspond to the property in the User.xml file,
Package com.tt;
/** Object Model
*
* @author taoyutong.pt
*
*
/public class User {
private int id;
private String name;
private int age;
Private String sex;
Private String location;
public void setlocation (String location) {
this.location = location;
}
Public String getLocation () {return
location;
}
public void Setgender (String gender) {
this.sex = gender;
}
Public String Getgender () {return
sex;
}
public void Setage (int age) {
this.age = age;
}
public int getage () {return age
;
}
public void SetName (String name) {
this.name = name;
}
Public String GetName () {return
name;
}
public void setId (int id) {
this.id = ID;
}
public int getId () {return
ID;
}
}
Userdao Interface:
Package com.tt;
Import java.sql.SQLException;
Import java.util.List;
/**
* Userdao
* @author taoyutong.pt * *
/Public
interface Userdao {
//Add public
int Insertuser (user user) throws SQLException;
Delete public
int deleteuser (int id) throws SQLException;
Change public
int updateuser (user user) throws SQLException;
Check public
User queryuser (int id) throws SQLException;
Public list<user> queryuserbydynamic (user user) throws SQLException;
}
Userdaoimpl Implementation class:
Package com.tt;
/** * Userdao Implementation class * * Import java.io.IOException;
Import Java.io.Reader;
Import java.sql.SQLException;
Import java.util.List;
Import com.ibatis.sqlmap.client.SqlMapClient;
public class Userdaoimpl implements userdao{//sqlmapclient private static sqlmapclient sqlmapclient; Static {try {reader reader = com.ibatis.common.resources.Resources. Getresourceasreader ("com/tt/sqlmapconfig.x
ML ");
Sqlmapclient = Com.ibatis.sqlmap.client.SqlMapClientBuilder. buildsqlmapclient (reader);
Reader.close ();
catch (IOException e) {e.printstacktrace (); @Override public int insertuser (user user) throws sqlexception{return (Integer) Sqlmapclient.insert ("Insertuser"
, user); @Override public int deleteuser (int id) throws sqlexception{return (Integer) sqlmapclient.delete ("DeleteUser", I
D);
@Override public int updateuser (user user) throws the sqlexception{return sqlmapclient.update ("UpdateUser", user); } @Override PubLIC User queryuser (int id) throws sqlexception{return (user) Sqlmapclient.queryforobject ("Selectuser", id); @Override public list<user> queryuserbydynamic (user user) throws sqlexception{return Sqlmapclient.queryforlis
T ("Selectusers", user);
}
}
Appmain.java Test
Package com.tt;
Import java.sql.SQLException;
public class Appmain {public
static void Main (String args[]) throws sqlexception{
Userdao Userdao = new Userdaoim PL ();
User User =new User ();
User.setage ();
User.setgender ("man");
User.setlocation ("Dalian");
User.setname ("Bulu");
System.out.println (user),//return Userdao.insertuser ID
user.setname ("tt");
System.out.println (Userdao.updateuser (user));/
}
}