mybatis入门程序
工程结构 在IDEA中新建了一个普通的java项目,新建文件夹lib,加入jar包,工程结构如图。
mybatis_入门程序一-工程结构图
1 2 3 4 5 6 # Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?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 > <environments 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://120.25.162.238:3306/mybatis001?characterEncoding=utf-8" /> <property name ="username" value ="root" /> <property name ="password" value ="123" /> </dataSource > </environment > </environments > </configuration >
映射文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?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 ="test" > <select id ="findUserById" parameterType ="int" resultType ="com.iot.mybatis.po.User" > SELECT * FROM user WHERE id=#{value} </select > <select id ="findUserByName" parameterType ="java.lang.String" resultType ="com.iot.mybatis.po.User" > SELECT * FROM user WHERE username LIKE '%${value}%' </select > </mapper >
在sqlMapConfig.xml中加载User.xml
1 2 3 4 <mappers > <mapper resource ="sqlmap/User.xml" /> </mappers >
程序代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 package com.iot.mybatis.po;import java.util.Date;public class User { private int id; private String username; private String sex; private Date birthday; private String address; public int getId () { return id; } public void setId (int id) { this .id = id; } public String getUsername () { return username; } public void setUsername (String username) { this .username = username; } public String getSex () { return sex; } public void setSex (String sex) { this .sex = sex; } public Date getBirthday () { return birthday; } public void setBirthday (Date birthday) { this .birthday = birthday; } public String getAddress () { return address; } public void setAddress (String address) { this .address = address; } @Override public String toString () { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]" ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 package com.iot.mybatis.first;import com.iot.mybatis.po.User;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.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class MybatisFirst { @Test public void findUserByIdTest () throws IOException { String resource = "SqlMapConfig.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.findUserById" , 1 ); System.out.println(user); sqlSession.close(); } @Test public void findUserByNameTest () throws IOException { String resource = "SqlMapConfig.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> list = sqlSession.selectList("test.findUserByName" , "小明" ); System.out.println(list); sqlSession.close(); } }
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 1857815974. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6ebc05a6] DEBUG [main] - ==> Preparing: SELECT * FROM user WHERE id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 1 User [id=1, username=王五, sex=2, birthday=null, address=null] DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6ebc05a6] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6ebc05a6] DEBUG [main] - Returned connection 1857815974 to pool.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 1596467899. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f282abb] DEBUG [main] - ==> Preparing: SELECT * FROM user WHERE username LIKE '%小明%' DEBUG [main] - ==> Parameters: DEBUG [main] - <== Total: 3 [User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州], User [id=22, username=陈小明, sex=1, birthday=null, address=河南郑州], User [id=25, username=陈小明, sex=1, birthday=null, address=河南郑州]] DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f282abb] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f282abb] DEBUG [main] - Returned connection 1596467899 to pool.
总结
在映射文件中通过parameterType指定输入参数的类型
在映射文件中通过resultType指定输出结果的类型
#{}
表示一个占位符号;
${}
表示一个拼接符号,会引起sql注入,所以不建议使用
selectOne
表示查询一条记录进行映射,使用selectList
也可以使用,只不过只有一个对象
selectList
表示查询出一个列表(参数记录)进行映射,不能够使用selectOne
查,不然会报下面的错:
1 org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3