CRUD operations in-mybatis Silicon Valley

Source: Internet
Author: User
Tags log4j

Project structure:



User entity Class Code:

Package Com.atguigu.mybatis.bean;public class User {private int id;private String name;private int age;public User () {Supe R ();} public User (int ID, String name, int.) {super (); this.id = Id;this.name = Name;this.age = age;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "User [id=" + ID + ", name=" + name + ", age=" + Age + "]";}}

Usermapper.xml Map File Code:

<?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= "Com.atguigu.mybatis.bean.userMapper" ><!--crud operations--><insert id= "AddUser" Parametertype= "User" >insert into Users (name,age) values (#{name},#{age}) </insert><delete id= "DeleteUser "Parametertype=" int ">delete from users where Id=#{id}</delete><update id=" UpdateUser "parametertype=" User ">update users set Name=#{name},age=#{age} where Id=#{id}</update><select id=" GetUser "parametertype= "int" resulttype= "User" >select * from users where Id=#{id}</select><select id= "GetAllUsers" resulttype= " User ">select * from users</select></mapper>

Usermapper Annotation Class code (either in XML or annotated):

Package Com.atguigu.mybatis.test2;import Java.util.list;import Org.apache.ibatis.annotations.delete;import Org.apache.ibatis.annotations.insert;import Org.apache.ibatis.annotations.select;import Org.apache.ibatis.annotations.update;import Com.atguigu.mybatis.bean.user;public interface UserMapper {@Insert (" Insert into users (name,age) values (#{name},#{age}) ' public int ' Add (user user); @Delete ("Delete from Users where Id=#{id}" public int Deletebyid (int id), @Update ("Update users set Name=#{name},age=#{age} where Id=#{id}") public int Update (User u Ser), @Select ("SELECT * from Users where Id=#{id}") Public User getById (int id), @Select ("SELECT * from users") public list< ; User> getAll ();}

Get the Mybatisutils code for the Sqlsessionfactory factory:

Package Com.atguigu.mybatis.utils;import Java.io.inputstream;import org.apache.ibatis.session.SqlSessionFactory; Import Org.apache.ibatis.session.sqlsessionfactorybuilder;public class Mybatisutils {public static sqlsessionfactory GetFactory () {String resource = "Conf.xml"; InputStream InputStream = MybatisUtils.class.getClassLoader (). getResourceAsStream (Resource); Sqlsessionfactory factory = new Sqlsessionfactorybuilder (). Build (InputStream); return factory;}}

Configuration file Conf.xml Code:

<?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><properties resource= "db.properties"/><!--define aliases for entity classes, simplifying references in SQL mapping XML files-->< typealiases><!--<typealias type= "Com.atguigu.mybatis.bean.User" alias= "User"/>--><!-- All classes under this package have their simple class name as the entity class name (for example: User class alias is user)--><package name= "Com.atguigu.mybatis.bean"/></typealiases> <!--development: Development mode work: Working mode--><environments default= "development" ><environment id= "development" ><transactionmanager type= "JDBC"/><datasource type= "pooled" ><property name= "Driver" value= "${ Driver} "/><property name=" url "value=" ${url} "/><property name=" username "value=" ${name} "/>< Property name= "Password" value= "${password}"/></datasource></environment></environments> <mappers><mapper resource= "Com/atguigu/mybatis/bean/usermapper.xml "/><mapper class=" Com.atguigu.mybatis.test2.UserMapper "/></mappers></ Configuration>

Test class Test2 Code:

Package Com.atguigu.mybatis.test2;import Java.util.list;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.junit.test;import Com.atguigu.mybatis.bean.user;import com.atguigu.mybatis.utils.mybatisutils;/* * Test: Implementation of XML for CRUD operations and implementation of annotations */public class Test2 {//-------------------------- The implementation of the------test XML @testpublic void Testadd () {sqlsessionfactory factory=mybatisutils.getfactory ();//default is manual commit Sqlsession Session=factory.opensession (); String statement= "Com.atguigu.mybatis.bean.userMapper.addUser"; int Insert=session.insert (statement, New User (-1, " KK ", 23));//Submit Transaction Session.commit (); Session.close (); SYSTEM.OUT.PRINTLN (insert);} @Testpublic void Testupdate () {sqlsessionfactory factory=mybatisutils.getfactory ();//default is manual commit Sqlsession session= Factory.opensession (TRUE); String statement = "Com.atguigu.mybatis.bean.userMapper.updateUser"; int update =session.update (statement,new User (3, "KKK111"); Session.close (); SYSTEM.OUT.PRINTLN (update);} @Testpublic void TeStdelete () {sqlsessionfactory factory=mybatisutils.getfactory ();//default is manual commit Sqlsession session=factory.opensession ( true); String statement = "Com.atguigu.mybatis.bean.userMapper.deleteUser"; int delete =session.delete (statement,3); Session.close (); SYSTEM.OUT.PRINTLN (delete);} @Testpublic void Testgetuser () {sqlsessionfactory factory=mybatisutils.getfactory ();//default is manual commit Sqlsession session= Factory.opensession (TRUE); String statement = "Com.atguigu.mybatis.bean.userMapper.getUser"; User User=session.selectone (statement, 1); Session.close (); SYSTEM.OUT.PRINTLN (user);} @Testpublic void Testgetall () {sqlsessionfactory factory=mybatisutils.getfactory ();//default is manual commit Sqlsession session= Factory.opensession (TRUE); String statement = "Com.atguigu.mybatis.bean.userMapper.getAllUsers"; List<user> list=session.selectlist (statement); Session.close (); SYSTEM.OUT.PRINTLN (list);} Implementation of the--------------------------------test annotations @testpublic void TestAdd2 () {sqlsessionfactory factory= Mybatisutils.getfactory (); Sqlsession Session=factorY.opensession (TRUE); Usermapper Mapper=session.getmapper (usermapper.class); int Add=mapper.add (New User ( -1, "SS"); Session.close (); System.out.println (add);}}

Database Configuration Code db.properties:

driver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/mybatisname=rootpassword=123456

The log4j configuration file can be added under src to print the log information:

--First Add Log4j-1.2.16.jar

-and then:

Log4j.properties (Way one)

        Log4j.properties,log4j.rootlogger=debug, console#consolelog4j.appender.console= org.apache.log4j.consoleappenderlog4j.appender.console.layout= org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d [%t]%-5p [%c]-%m% nlog4j.logger.java.sql.resultset=infolog4j.logger.org.apache=infolog4j.logger.java.sql.connection= Debuglog4j.logger.java.sql.statement=debuglog4j.logger.java.sql.preparedstatement=debug

Log4j.xml ( way two )

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE log4j:configuration SYSTEM "log4j.dtd" ><log4j:configuration xmlns:log4j= "http://jakarta.apache.org/ log4j/"><appender name=" STDOUT "class=" Org.apache.log4j.ConsoleAppender "><layout class=" Org.apache.log4j.PatternLayout "><param name=" Conversionpattern "value="%-5p%d{mm-dd hh:mm:ss,sss}%m  (%F :%l) \ n "/></layout></appender><logger name=" java.sql "><level value=" Debug "/></ Logger><logger name= "Org.apache.ibatis" ><level value= "Debug"/></logger><root>< Level value= "Debug"/><appender-ref ref= "STDOUT"/></root></log4j:configuration>

CRUD operations in-mybatis Silicon Valley

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.