CRUD operation of mybatis, Silicon Valley-mybatiscrud

Source: Internet
Author: User

CRUD operation of mybatis, Silicon Valley-mybatiscrud

Project Structure:



User entity code:

package com.atguigu.mybatis.bean;public class User {private int id;private String name;private int age;public User() {super();}public User(int id, String name, int age) {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 age) {this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age + "]";}}

UserMapper. xml ing file code:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. atguigu. mybatis. bean. userMapper "> <! -- CRUD operation --> <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 annotation ):

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 user);@Select("select * from users where id=#{id}")public User getById(int id);@Select("select * from users")public List<User> getAll();}

Obtain the MybatisUtils code of 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 object classes to simplify SQL ing references in xml files --> <typeAliases> <! -- <TypeAlias type = "com. atguigu. mybatis. bean. User" alias = "User"/> --> <! -- All classes in this package are named as entity classes (for example, the alias of the User class 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 {// ---------------------------------- Implementation of test XML @ Testpublic void testAdd () {SqlSessionFactory factory = MybatisUtils. getFactory (); // SqlSession session = factory submitted manually by default. openSession (); String statement = "com. atguigu. mybatis. bean. userMapper. addUser "; int insert = session. insert (statement, new User (-1, "KK", 23); // submit the transaction session. commit (); session. close (); System. out. println (insert) ;}@ Testpublic void testUpdate () {SqlSessionFactory factory = MybatisUtils. getFactory (); // by default, SqlSession session = factory is submitted manually. openSession (true); String statement = "com. atguigu. mybatis. bean. userMapper. updateUser "; int update = session. update (statement, new User (3, "KKK111", 25); session. close (); System. out. println (update) ;}@ Testpublic void testDelete () {SqlSessionFactory factory = MybatisUtils. getFactory (); // by default, SqlSession session = factory is submitted manually. 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 (); // by default, SqlSession session = factory is submitted manually. 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 (); // by default, SqlSession session = factory is submitted manually. 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 annotation @ 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", 34); session. close (); System. out. println (add );}}

Database Configuration code db. properties:

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

You can add the log4j configuration file under src to print the log information:

--> First add log4j-1.2.16.jar

--> Then:

Log4j. properties (method 1)

        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 (method 2)

<?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>

Related Article

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.