Mybatis and spring integration of mapper agent development

Source: Internet
Author: User
Tags aliases

F:\1ziliao\mybatis\ Code

1.1 Sqlmapconfig.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Configuration
Public "-//mybatis.org//dtd Config 3.0//en"
"Http://mybatis.org/dtd/mybatis-3-config.dtd" >

<configuration>

<!--configuration of MyBatis operating parameters via setting
Note that setting the operating parameters will affect the operation of MyBatis, be sure to pay attention!
-
<settings>
<!--The total switch for delayed loading--
<setting name= "lazyloadingenabled" value= "true"/>
<!--set to False for load-on-demand
<setting name= "aggressivelazyloading" value= "false"/>
<!--turn on level two cache--
<setting name= "cacheenabled" value= "true"/>
</settings>

<!--definition Aliases--

<typeAliases>
<!--single alias definition
Type: Class path
Alias: Aliases
-
<!--<typealias type= "Cn.itcast.mybatis.po.User" alias= "User"/>-
<!--Batch Configuration
Specifies the package path of the Pojo, and automatically scans the Pojo definition alias under the package, with the alias class name (either lowercase or uppercase)
-
<package name= "Cn.itcast.mybatis.po"/>
<!--If you scan Pojo in multiple packages, write multiple package-->
<!--<package name= ""/>--
</typeAliases>

</configuration>

1.2 configuring in the Spring container sqlsessionfactory Applicationcontext.xml
<beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "Http://www.springframework.org/schema/mvc"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp//Www.springframework.org/schema/mvchttp//www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-3.2.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!--Configure the data source DataSource--><!--load profile--><context:property-placeholder location= "Classpath: Db.properties "/><!--database connection pool--><bean id=" DataSource "class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > <property name= "driverclassname" value= "$ {jdbc.driver} "/> <property name=" url "value=" ${jdbc.url} "/> <property name=" username "value=" ${j  Dbc.username} "/> <property name=" password "value=" ${jdbc.password} "/> <property name=" MaxActive " Value= "Ten"/> <property name= "Maxidle" value= "5"/></bean> <!--configuration Sqlsessionfactory--><b Ean id= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean" > <!--configuration data source-<property name= "DataSource" ref= "DataSource" /> <!--load MyBatis configuration file--<property name= "configlocation" value= "Classpath:SqlMapConfig.xml"/></b ean><!--Original DAO--><!--<bean id= "Userdao"class= "Cn.itcast.mybatis.dao.UserDaoImpl" > <property name= "sqlsessionfactory" ref= "Sqlsessionfactory"/></ Bean>-<!--mapper Agent configuration--><!--<bean id= "Usermapper"class= "Org.mybatis.spring.mapper.MapperFactoryBean" >specifying the Mapper interface<property name= "Mapperinterface" value= "Cn.itcast.mybatis.mapper.UserMapper"/>Inject Sqlsessionfactory<property name= "Sqlsessionfactory" ref= "Sqlsessionfactory"/> </bean> <!--Creating a Mapper proxy object scanner using the Mapper scanner automatically scans the mapper under the package to create a proxy object registered in the spring container with the Bean's ID as the class name (first letter lowercase)-<beanclass= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <!--Specify the package path to scan, if you want to scan multiple packages, use a comma-delimited half-width Note: If you are using a scanner, you do not need to load mapper in Sqlmapconfig.xml, Mapper.xml and Mapper.java in the same directory with the same name 
    --<property name= "Basepackage" value= "Cn.itcast.mybatis.mapper"/> <property name= "Sqlsessionfactoryb Eanname "value=" Sqlsessionfactory "></property> </bean></beans>
1.3 Interface Mapper.java and Mapper.xml
 Public InterfaceUsermapper {//query user information based on user ID     PublicUser Finduserbyid (intIdthrowsException; //querying users using Resultmap     PublicUser Finduserbyidresultmap (intIdthrowsException; //Fuzzy query based on user name     PublicList<user> Finduserbyname (String username)throwsException; //Insert User     Public voidInsertuser (user user)throwsException; //Update User     Public voidUpdateUser (user user)throwsException;}
<?xml version= "1.0" encoding= "UTF-8"? ><!DOCTYPE mapperpublic"-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><!--A mapper mapping file is configured in SQL statements that ultimately encapsulate SQL statements into Mappedstatement objects namespace namespaces are better for isolating SQL statements. Easy to manage SQL Note: The late-mybatis mapper Agent Development mode when namespace has a special role, as follows: namespace equals the Mapper interface Classpath, so that the mapping file to find the corresponding Mapper interface is which--><mapper namespace= "Cn.itcast.mybatis.mapper.UserMapper" ><!--Open Level two cache--><!--<cache type= " Org.mybatis.caches.ehcache.EhcacheCache "/>--><!--querying a user's information based on user ID select: For queries, main configuration SQL statements, input parameter types, output result types Finally, the content configured in the SELECT tag is encapsulated into the Mappedstatement object, which can be Select is called a Statementid: uniquely identifies an SQL statement under namespace, which is called the Idparametertype of statement: Specifies the type of input parameter (simple type, custom Pojo) #{} : Represents a placeholder symbol that prevents SQL injection #{value}:value representing the value of the receive input parameter, if the input parameter being received is a simple type, #{} You can write value or other name Resulttype: Map the SQL query result set to a Java object to map the values of multiple columns to an object, you need to define the Pojo, The Resulttype mapping rule is that the SQL query column names and Pojo property names must be consistent in order to complete the mapping Resulttype the Java objects that are mapped by the specified single record--><select id= "Finduserbyid" parametertype= "int" resulttype= "user" >SELECT id,username,birthday,sex,address from USER WHERE ID=#{id}</select><!--use Resultmap to make a corresponding relationship between the column name and the Pojo property value, complete the mapping ID: uniquely identifies an element type: The Pojo type of the final mapping--><resultmap type= "user" id= "Queryuserresultmap" > <!--ID identity Column column column: Uniquely identified in the result set property: The attribute name of the Pojo specified by the type that uniquely identifies the column to which it is mapped--<id column= "id_" property= "id"/> <!--If the result set has multiple columns combined into a unique identity, define two ID tags-<!--result: normal column--    > <result column= "username_" property= "username"/> <result column= "Birthday_" property= "Birthday"/> <result column= "sex_" property= "Sex"/> <result column= "Address_" property= "Address"/></resultmap> <!--Query the user, use Resultmap to complete the result mapping--><select id= "Finduserbyidresultmap" parametertype= "int" resultmap= " Queryuserresultmap ">SELECT ID id_,username username_,birthday birthday_,sex sex_,address address_ from USER WHERE ID=#{id}</select><!--Query user Information list resulttype based on user name: Regardless of the number of result set records, RESUTTYPE Specifies that the Java object mapped by a single record resulttype mapping rule is that the SQL query column name and Pojo property name must be consistent to complete the mapping ${}: Represents a SQL concatenation symbol, which is equivalent to the concatenation of strings: "Select* FROM USER WHERE username like '% ' + ${} for string + "% '"${}: If the receive input parameter is a simple type, ${} can only write value${} implementation of SQL stitching is not able to prevent SQL injection. --<select id= "Finduserbyname" parametertype= "java.lang.String" resulttype= "Cn.itcast.mybatis.po.User" >SELECT* FROM USER WHERE username like '%${value}% ' </select><!--Adding a user requires the input parameter to be multiple values if the incoming simple type is unable to meet the requirements. The input parameter type can be defined as Pojo (Cn.itcast.mybatis.po.User includes multiple properties) #{} How do I get the value of an object? #{} is an expression that reads the value of an object by Ognl: property. Properties. Properties.. Until the value of the property in the object is read over the MySQL database via select last_insert_id (); Gets the value of the self-increment primary key after the INSERT statement executes last_insert_id () Gets the primary key of the new record--><insert id= "Insertuser" parametertype= "Cn.itcast.mybatis.po.User" > <!--Keyproperty: Sets the primary key value to which property of the input parameter is set to the user's id attribute in the SQL statement in Order:selectkey before or after the INSERT statement is executed, which is set to"After"resulttype:select last_insert_id () query out the value--<selectkey keyproperty= "id" order= "after" resulttype= "Java.lang.Integer" >Select last_insert_id ()</selectKey>INSERT INTO User (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address});</insert><!--use MySQL uuid to generate primary key--><!--<insert id= "Insertuser" parametertype= " Cn.itcast.mybatis.po.User ">Keyproperty: Sets the primary key value to which property of the input parameter is set to the user's id attribute order:select uuid () executes the UUID as the primary key before the insert executes, setting the primary key value to the user's property R Esulttype:select uuid () query out value<selectkey keyproperty= "id" order= "before" resulttype= "java.lang.String" >Select UUID ()</selectKey>INSERT INTO User (id,username,birthday,sex,address) VALUES (#{id},#{username},#{birthday},#{sex},#{address});</insert>--><!--Modify user--><update id= "updateUser" parametertype= "Cn.itcast.mybatis.po.User" >Update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}</update><!--Delete User--><delete id= "deleteuser" parametertype= "int" >Delete from user where ID=#{id}</delete></mapper>
1.4 Spring and mybatis Integrated Generation Agent object method 2 scanner

Mybatis and spring integration of mapper agent development

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.