Mysql ready early
create database cong use cong; create table account( id int primary key auto_increment, name varchar(40), money float )character set utf8 collate utf8_general_ci; insert into account(name,money) values('aaa',1000); insert into account(name,money) values('bbb',1000); insert into account(name,money) values('ccc',1000);
1.maven create a project, import dependence
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cong</groupId> <artifactId>mybatis_account_CRUD_annotation</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
2. entity class
package com.cong.pojo; public class Account { private int id; private String name; private float money; @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } 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 float getMoney() { return money; } public void setMoney(float money) { this.money = money; } }
3. Profiles 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> <typeAliases> <package name="com.cong.pojo"></package> </typeAliases> <environments default="account"> <environment id="account"> <!-- 使用JDBC事物管理 --> <transactionManager type="JDBC"></transactionManager> <!-- 数据库连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/cong"></property> <property name="username" value="the root " > </ Property> <Property name = " password " value = " 123456 " > </ Property> </ the dataSource> </ Environment> </ Environments> <-! position specified mapping configuration file, a mapping configuration file refers to each separate profiles mapper If the annotation is configured, it should here be specified class attribute annotated mapper fully qualified class name -> <by mappers> <mapper class = " com.cong.mapper. AccountMapper " > </ Mapper> </ by mappers> </ Configuration>
4.log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
5.mapper Interface
package com.cong.mapper; import com.cong.pojo.Account; import org.apache.ibatis.annotations.*; import java.util.List; public interface AccountMapper { @Select("select * from account") List<Account> findAll(); @Select("select * from account where id = #{id}") Account findById(int id); @Select("select * from account where name like #{name}") //@Select("select * from account where name like '%${value}%'") List<Account> findByName(String name); @Select("select count(*) from account") int findTotal(); @Insert("insert into account(name,money) values(#{name},#{money})") //@SelectKey(statement="select last_insert_id()",before=false,keyProperty="id",resultType=Integer.class,keyColumn="id") @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id"//saveAccount (the Account the Account);intreturns the id auto-increment field, the above statement is the same effect//) The return value is the impact of the entry of the database, instead of inserting the id, want to get auto-incremented id, need only visit once this object can be. @Delete ( " Delete from WHERE ID Account ID = # {} " ) void deleteAccount ( int ID); @Update ( " Update Account SET name = # {name}, {Money Money = #} # {WHERE ID = ID} " ) void updateAccount (Account the Account); / * * * we are now operating is the object Account, if the Account property more, * we just update a single attribute Account, do we re-generate a pass into Account? * No, we can use this form of the following Update * We use @Param parameters, just pass parameters to our interest. * Incoming parameter is name, and it is re-defined as the n in @Param, * then it can be used directly in Sql by $ {n}, this is actually a function parameters and to solve the impedance mismatch parameter Sql . * / @Update("update account set name=#{n} where id = #{i}") void updateAccountByParam(@Param("n")String name,@Param("i")int id); }
6. Test class
import com.cong.mapper.AccountMapper; import com.cong.pojo.Account; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.List; public class TestCRUD { InputStream inputStream = null; SqlSession sqlSession = null; AccountMapper mapper = null; @Test public void findAll() { List<Account> accounts = mapper.findAll(); for (Account account : accounts) { System.out.println(account.toString()); } } @Test public void findById() { Account account = mapper.findById(2); System.out.println(account.toString()); } @Test public void findByName() { List<Account> accounts = mapper.findByName("%on%");//like #{name}写法 // List<Account> accounts = mapper.findByName("on");//like ‘%${value}%’ 写法 for (Account account : accounts) { System.out.println(account.toString()); } } @Test public void findTotal(){ int accountTotal = mapper.findTotal(); System.out.println("account total:" + accountTotal); } @Test public void save() { The Account the Account = new new the Account (); account.setName ( " Cong " ); account.setMoney (1000f); mapper.saveAccount (the Account); // write a return from growth in the mapper objects id, the so objects will be here id attribute contains the System. OUT .println (account.toString ()); } @Test public void Update () { the Account Account = new new the Account (); account.setName ( " Cong " ); account.setMoney ( 222 ); Account .setId ( 10); Mapper.updateAccount (Account); } @Test public void updateByParam () { String name = " Rainbow Cai " ; int ID = . 4 ; mapper.updateAccountByParam (name, ID); } @Test public void deleteAccount () { Mapper .deleteAccount ( 28 ); } @Before // performed prior to the test method of performing public void the init () throws Exception { // 1. reads the configuration file to generate an input stream of bytes = Resources.getResourceAsStream inputStream ( " the SqlMapConfig.xml " ); // 2. Get the SqlSessionFactoryBuilder a SqlSessionFactory Factory = new new the SqlSessionFactoryBuilder () Build (inputStream);. // 3. The SqlSession plant using SQLSESSION = factory.openSession (); / / 4. Create SqlSession mapper interface proxy object mapper = sqlSession.getMapper (AccountMapper. class ); // 5. the mapper then execute the method using the proxy object interface } @After // performed after performing the test method public void Close () throws Exception { // commit the transaction, additions and deletions to the need to commit the transaction, the database will change sqlSession.commit (); // release resources sqlSession.close (); inputStream.close (); } }
7. Directory Structure
These notes have been able to provide an alternative function common SQL statement, and if you need more complex than this, that or the use of xml configuration for the best.
You can really control and coordinate the relationship between the SQL function or directly write SQL is appropriate, the SQL unified management is also common practice to place.
Another point: Annotation and Xml configuration can exist at the same time, this is a must.
Some of our Sql particularly long and complex function, in the code itself is not very easy to manage, thus providing a unified xml management is still very necessary.
Note This article notes that, and Spring AOP, IoC characteristics not related mybatis itself provides,
What we are doing is to use mybatis alone for development. As for the combination of mybatis and Spring,
In fact, the mybatis of SqlSessionFactory delegate for Spring management, coupled with the IoC characteristics, can save a lot of code amount at the time of use.
Reference: https://isilic.iteye.com/blog/1810782