Java data Access (3): MyBatis

Source: Internet
Author: User

Maven

        <!--import MySQL database link jar--        <dependency>            <groupId>mysql</groupId>            < artifactid>mysql-connector-java</artifactid>            <version>5.1.6</version>        </ Dependency>        <!--import MyBatis Package--        <dependency>            <groupid>org.mybatis</groupid >            <artifactId>mybatis</artifactId>            <version>3.1.1</version>        </ Dependency>

Mybatis-config.xml configuration file

<?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>    Default= "Development" >        <environment id= "Development" >            < TransactionManager type= "JDBC"/>            <datasource type= "Pooled" >                <property name= "Driver" value= " Com.mysql.jdbc.Driver "/>                <property name=" url "value=" Jdbc:mysql://localhost:3306/test2 "/>                < Property name= "username" value= "root"/>                <property name= "password" value= "sa1234$"/>            </ datasource>        </environment>    </environments>    <mappers>        <mapper Resource= "Userdaomapper.xml"/>    </mappers></configuration>

Create an entity class

 PackageMy.pojo; Public classUser {Private intuserId; PrivateString UserName; PrivateString password; PrivateString Comment;  Public intgetUserId () {returnuserId; }         Public voidSetuserid (intuserId) {         This. UserId =userId; }           PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }             PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }             PublicString getcomment () {returncomment; }     Public voidsetcomment (String comment) { This. Comment =comment; }}

Create a mapping file

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "My.dao.UserDao" > <insert id= "Insert" parametertype= "My.pojo.User" >INSERT INTO User (Username,password,comment) VALUES (#{username},#{password},#{comment})</insert> <update id= "Update" parametertype= "My.pojo.User" >Update user Set UserName=#{username},password=#{password},comment=#{comment} where UserName=#{username}</update> <delete id= "delete" parametertype= "int" >Delete from user where UserName=#{username}</delete> <select id= "Findbyusername" parametertype= "String" resulttype= "My.pojo.User" >Select* FROM user where username=#{username}</select> <select id= "Countall" resulttype= "int" >Select COUNT (*) c from user; </select> <select id= "SelectAll" resulttype= "My.pojo.User" >Select*From the user order by userName ASC</select> <select id= "FindByID" parametertype= "Int" resulttype= "My.pojo.User" >Select*From user where userId=#{userid}</select></mapper>

Create DAO

 PackageMy.dao;Importjava.util.List;ImportMy.pojo.User; Public InterfaceUserdao { Public intInsert (user user);  Public intUpdate (user user);  Public intDelete (String userName);  PublicList<user>SelectAll ();  Public intCountall ();  PublicUser findbyusername (String userName);  PublicUser FindByID (intuserId);}

Test

 PackageMy.common;Importjava.io.IOException;ImportJava.io.Reader;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder; Public classSessionhelper {StaticSqlsessionfactory Factory;  Public StaticSqlsession getsession ()throwsIOException {if(Factory = =NULL) {Reader Reader= Resources.getresourceasreader ("Mybatis-config.xml"); Factory=NewSqlsessionfactorybuilder (). build (reader); } sqlsession Session=factory.opensession (); returnsession; }}

 PackageMy.main;ImportMy.dao.UserDao;ImportMy.pojo.User;Importorg.apache.ibatis.session.SqlSession;Importmy.common.*; Public classApp { Public Static voidMain (string[] args) {sqlsession session=NULL; Try{Session=sessionhelper.getsession (); Userdao Userdao= Session.getmapper (Userdao.class); User User= Userdao.findbyid (18);            System.out.println (User.getusername ());        Session.commit (); } Catch(Exception e) {e.printstacktrace ();        Session.rollback (); } finally {            if(Session! =NULL) {session.close (); }        }    }}

Java data Access (3): MyBatis

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.