1, convenient to view the log information, create log4j.propertiesunder classpath , mybatis default use log4j As output log information
# Global Logging Configurationlog4j.rootlogger=DEBUG, stdout# Console output...log4j.appender.stdout =Org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout= Org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t]-%m%n
2. Create the sqlmapconfig.xml under classpath , as follows:
Sqlmapconfig.xml is the mybatis Core configuration file with the configuration content of the top file as the data source, transaction management.
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" ><Configuration> <!--environments configuration will be abolished after the integration with spring - <Environmentsdefault= "Development"> <EnvironmentID= "Development"> <!--using JDBC Transaction management - <TransactionManagertype= "JDBC" /> <!--Database Connection Pool - <DataSourcetype= "Pooled"> < Propertyname= "Driver"value= "Com.mysql.jdbc.Driver" /> < Propertyname= "url"value= "Jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8" /> < Propertyname= "username"value= "root" /> < Propertyname= "Password"value= "MySQL" /> </DataSource> </Environment> </Environments> </Configuration>
3. Create PO Class
The PO class is used as a mybatis for SQL Mapping,and thepo class usually corresponds to a database table. User.java as follows:
class User { privateint ID; Private String username; // User name Private String sex; // Sex Private Date birthday; // Birthday Private String address; // Address Get/set ...
}
4. Configure the PO mapping file
Create a SQL mapping file under the Sqlmap directory under Classpath Users.xml, and configure the SQL statement in the mapping file.
User.xml(Original ibatis name ),mapper Agent Development Map file name is called xxxmapper.xml , such as:usermapper.xml,itemsmapper.xml
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "><!--namespace namespaces, the role is to classify the SQL management, understand the SQL Isolation Note: The use of Mapper proxy method development, namespace has a special role -<Mappernamespace= "Test"> <!--Configuring many SQL statements in a mapping file - <!--Requirements: Querying the records of user tables by ID - <!--Execute database Query ID with select: The SQL in the identity map file encapsulates the SQL statement into the Mappedstatement object, so ID is called statement ID parametertype: Specifies the type of the input parameter, which The specified int #{} represents a placeholder symbol #{id}: The ID of the input parameter is received, the parameter name is the ID, if the input parameter is a simple type, the parameter name in #{} can be arbitrary, can be value or another name resulttype: Specify SQL Output The result of the mapped Java object type, select Specifies that Resulttype represents a Java object that maps a single record. - <SelectID= "Finduserbyid"ParameterType= "int"Resulttype= "Cn.itcast.mybatis.po.User">SELECT * from USER WHERE Id=#{value}</Select> <!--based on the user name fuzzy query user information, may return multiple Resulttype: Specifies that the single record is mapped by the Java object Type ${}: Represents the concatenation of the SQL string, the contents of the received parameters are not decorated with any adornment in SQL. Use ${} to stitch sql, causing SQL injection ${value}: Receive input parameter contents, if the incoming type is a simple type, ${} can only use the value - <SelectID= "Finduserbyname"ParameterType= "Java.lang.String"Resulttype= "Cn.itcast.mybatis.po.User">SELECT * from USER WHERE username like '%${value}% '</Select> <!--Add User parametertype: Specifies that the input parameter type is Pojo (including user information) #{} Specifies the property name of the Pojo, receives the property value of the Pojo object, MyBatis gets the property value of the object by OGNL - <InsertID= "Insertuser"ParameterType= "Cn.itcast.mybatis.po.User"> <!--returns the primary key of the inserted data to the user object, SELECT last_insert_id (): Gets the primary key value of the first insert in the record, only applies with the self-increment primary key Keypro Perty: Sets the query-to-primary key value to the parametertype of the specified object Order:select the last_insert_id () execution order, relative to the INSERT statement resulttype: Specify S Result type of elect last_insert_id () - <SelectkeyKeyproperty= "id"Order= "after"Resulttype= "Java.lang.Integer">SELECT last_insert_id ()</Selectkey>INSERT INTO User (username,birthday,sex,address) value (#{username},#{birthday},#{sex},#{address})<!--use the MySQL uuid () to generate the primary key execution process: First the primary key is obtained through the UUID (), the primary key is set to the id attribute of the user object, and then the id attribute value is taken out of the user object when insert executes. - <!--<selectkey keyproperty= "id" order= "before" resulttype= "java.lang.String" > select UUID () < /selectkey> INSERT INTO User (id,username,birthday,sex,address) value (#{id},#{username},#{birthday},#{sex},#{add Ress}) - </Insert> <!--Delete User Delete user by ID, need to enter ID value - <DeleteID= "DeleteUser"ParameterType= "Java.lang.Integer">Delete from user where Id=#{id}</Delete> <!--Update user analysis based on ID: The ID of the incoming user needs the update information of the incoming user parametertype specify the user object, including the ID and update information, note that the ID must exist #{id}: Get the id attribute value from the input user object - <UpdateID= "UpdateUser"ParameterType= "Cn.itcast.mybatis.po.User">update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where Id=#{id } </Update> </Mapper>
5. Add the User.xml mapping file to the Sqlmapconfig.xml
< mappers > < resource= "Sqlmap/user.xml"/></mappers>
6. Test code
Public classMybatis_first {//Session Factory Privatesqlsessionfactory sqlsessionfactory; @Before Public voidCreatesqlsessionfactory ()throwsIOException {//configuration fileString resource = "Sqlmapconfig.xml"; InputStream InputStream=Resources.getresourceasstream (Resource); //use Sqlsessionfactorybuilder to create Sqlsessionfactory from an XML configuration fileSqlsessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); } //query user information by ID@Test Public voidTestfinduserbyid () {//DB Session InstanceSqlsession sqlsession =NULL; Try { //create a DB session instance sqlsessionSqlsession =sqlsessionfactory.opensession (); //querying individual records, querying user information based on user IDUser user = Sqlsession.selectone ("Test.finduserbyid", 10); //Output User InformationSystem.out.println (user); } Catch(Exception e) {e.printstacktrace (); } finally { if(Sqlsession! =NULL) {sqlsession.close (); } } } //Fuzzy query user information based on user name@Test Public voidTestfinduserbyusername () {//DB Session InstanceSqlsession sqlsession =NULL; Try { //create a DB session instance sqlsessionSqlsession =sqlsessionfactory.opensession (); //querying individual records, querying user information based on user IDlist<user> list = sqlsession.selectlist ("Test.finduserbyusername", "Zhang"); System.out.println (List.size ()); } Catch(Exception e) {e.printstacktrace (); } finally { if(Sqlsession! =NULL) {sqlsession.close (); } } }}
1, the basic crud of MyBatis