test表有两个字段,id为自增主键。
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>MyBatis</artifactId> <name>MyBatis</name> <version>1.0</version> <groupId>chenwc</groupId> <packaging>jar</packaging> <properties> <java.version>1.8</java.version> <slf4j.version>1.7.36</slf4j.version> <log4j.version>1.2.17</log4j.version> <mybatis.version>3.5.11</mybatis.version> <mysql-connector-java.version>8.0.30</mysql-connector-java.version> <maven.compiler.plugin.version>3.6.1</maven.compiler.plugin.version> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-reload4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <type>pom</type> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.plugin.version}</version> </plugin> </plugins> </build> </project>
存放位置:src/main/resources
<?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> <settings> <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!-- 和Spring整合后environment配置都会被干掉 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理,目前由mybatis来管理 --> <transactionManager type="JDBC" /> <!-- 数据库连接池,目前由mybatis来管理 --> <dataSource type="POOLED"> <!--有关于mysql数据库的各种信息--> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ueditorminio?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!--在maven项目中会默认读取src/main/resources/mapper目录下的文件,其他目录需要单独设置路径--> <!--在Eclipse的java项目中,会读取mapper包下的文件--> <!--将操作配置文件TestMapper.xml系添加进mapper--> <mapper resource="mapper/TestMapper.xml"/> </mappers> </configuration>
package com.chenwc.util; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; /** * 获取 sqlsession 的工具类 * @author chenwc */ public class MybatisSessionUtil { public static SqlSession getSession() { SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); try { //在maven项目中getResourceAsStream会默认读取src/main/resources目录下的文件,其他目录需要单独设置路径 return sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("SqlMapConfig.xml")).openSession(); } catch (IOException e) { e.printStackTrace(); } return null; } }
package com.chenwc.entity; import java.io.Serializable; /** * 数据库表 test 的实体类 * @author chenwc */ public class Test implements Serializable { private String id; private String uuid; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
<?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不需要是完全的类名 --> <mapper namespace="TestMapper"> <!-- 通过id查询是否存在 --> <select id="countById" parameterType="java.lang.String" resultType="int"> select count(*) from test where id = ${id} </select> <!--如果不想使用实体类,resultType可以设置成Map--> <select id="getById" parameterType="java.lang.String" resultType="com.chenwc.entity.Test"> select * from test where id = ${id} </select> <select id="getByIdParameterByMap" parameterType="java.util.Map" resultType="com.chenwc.entity.Test"> select * from test where id = #{id} </select> <!--如果不想使用实体类,resultType可以设置成Map--> <select id="selectAll" resultType="java.util.Map"> select * from test </select> <select id="selectAllByEntity" resultType="com.chenwc.entity.Test"> select * from test </select> </mapper>
package com.chenwc.dao; import com.chenwc.entity.Test; import org.apache.ibatis.session.SqlSession; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Dao层 * @author chenwc */ public class TestDao { public static int countById(String id, SqlSession session){ // 第一个参数是mapper.xml里的namespace+MappedStatement对应的id int rint = session.selectOne("TestMapper.countById", id); // 不要忘记提交,SqlSession默认不自动提交 session.commit(); return rint; } public static Test getById(String id, SqlSession session){ //如果不想使用实体类,查询结果可以使用Map<String, Object>,类型需要和mapper文件中一致 Test test = session.selectOne("TestMapper.getById", id); session.commit(); return test; } public static Test getByIdParameterByMap(String id, SqlSession session){ //如果不想使用实体类,查询结果可以使用Map<String, Object>,类型需要和mapper文件中一致 Map<String, String> idMap = new HashMap<>(); idMap.put("id", id); Test test = session.selectOne("TestMapper.getByIdParameterByMap", idMap); session.commit(); return test; } public static List<Map<String, Object>> selectAll(SqlSession session){ //如果不想使用实体类,查询结果可以使用List<Map<String, Object>>,类型需要和mapper文件中一致 List<Map<String, Object>> list = session.selectList("TestMapper.selectAll"); session.commit(); return list; } public static List<Test> selectAllByEntity(SqlSession session){ //如果不想使用实体类,查询结果可以使用List<Map<String, Object>>,类型需要和mapper文件中一致 List<Test> list = session.selectList("TestMapper.selectAllByEntity"); session.commit(); return list; } }
package com.chenwc; import com.chenwc.dao.TestDao; import com.chenwc.entity.Test; import com.chenwc.util.MybatisSessionUtil; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; /** * 测试 * @author chenwc */ public class Main { private static final Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args){ SqlSession session = MybatisSessionUtil.getSession(); if (null == session){ return; } Test data = TestDao.getById("360881597623000", session); Test data2 = TestDao.getByIdParameterByMap("360881597623000", session); int count = TestDao.countById("360881597666500", session); List<Map<String, Object>> list = TestDao.selectAll(session); List<Test> list2 = TestDao.selectAllByEntity(session); log.info(String.valueOf(count)); log.info(data.getId()); log.info(data.getUuid()); log.info(list.toString()); try { session.clearCache(); session.close(); }catch (Exception e){ e.printStackTrace(); } } }
log4j.rootLogger=info,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %-5p %-5L --- [%-5t] %-10c : %m %n
mysql-connector-java-8.0.30.jar
mybatis-3.5.11.jar
slf4j-api-1.7.36.jar
log4j-1.2.17.jar
slf4j-log4j12-1.7.7.jar
存放位置:src,这个存放位置和 maven 项目的位置不同
<?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> <settings> <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!-- 和Spring整合后environment配置都会被干掉 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理,目前由mybatis来管理 --> <transactionManager type="JDBC" /> <!-- 数据库连接池,目前由mybatis来管理 --> <dataSource type="POOLED"> <!--有关于mysql数据库的各种信息--> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ueditorminio?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!--在maven项目中会默认读取src/main/resources/mapper目录下的文件,其他目录需要单独设置路径--> <!--在Eclipse的java项目中,会读取mapper包下的文件--> <!--将操作配置文件TestMapper.xml系添加进mapper--> <mapper resource="mapper/TestMapper.xml"/> </mappers> </configuration>
package com.chenwc.util; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; /** * 获取 sqlsession 的工具类 * @author chenwc */ public class MybatisSessionUtil { public static SqlSession getSession() { SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); try { //在maven项目中getResourceAsStream会默认读取src/main/resources目录下的文件,其他目录需要单独设置路径 return sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("SqlMapConfig.xml")).openSession(); } catch (IOException e) { e.printStackTrace(); } return null; } }
package com.chenwc.entity; import java.io.Serializable; /** * 数据库表 test 的实体类 * @author chenwc */ public class Test implements Serializable { private String id; private String uuid; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
<?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不需要是完全的类名 --> <mapper namespace="TestMapper"> <!-- 通过id查询是否存在 --> <select id="countById" parameterType="java.lang.String" resultType="int"> select count(*) from test where id = ${id} </select> <!--如果不想使用实体类,resultType可以设置成Map--> <select id="getById" parameterType="java.lang.String" resultType="com.chenwc.entity.Test"> select * from test where id = ${id} </select> <select id="getByIdParameterByMap" parameterType="java.util.Map" resultType="com.chenwc.entity.Test"> select * from test where id = #{id} </select> <!--如果不想使用实体类,resultType可以设置成Map--> <select id="selectAll" resultType="java.util.Map"> select * from test </select> <select id="selectAllByEntity" resultType="com.chenwc.entity.Test"> select * from test </select> </mapper>
package com.chenwc.dao; import com.chenwc.entity.Test; import org.apache.ibatis.session.SqlSession; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Dao层 * @author chenwc */ public class TestDao { public static int countById(String id, SqlSession session){ // 第一个参数是mapper.xml里的namespace+MappedStatement对应的id int rint = session.selectOne("TestMapper.countById", id); // 不要忘记提交,SqlSession默认不自动提交 session.commit(); return rint; } public static Test getById(String id, SqlSession session){ //如果不想使用实体类,查询结果可以使用Map<String, Object>,类型需要和mapper文件中一致 Test test = session.selectOne("TestMapper.getById", id); session.commit(); return test; } public static Test getByIdParameterByMap(String id, SqlSession session){ //如果不想使用实体类,查询结果可以使用Map<String, Object>,类型需要和mapper文件中一致 Map<String, String> idMap = new HashMap<>(); idMap.put("id", id); Test test = session.selectOne("TestMapper.getByIdParameterByMap", idMap); session.commit(); return test; } public static List<Map<String, Object>> selectAll(SqlSession session){ //如果不想使用实体类,查询结果可以使用List<Map<String, Object>>,类型需要和mapper文件中一致 List<Map<String, Object>> list = session.selectList("TestMapper.selectAll"); session.commit(); return list; } public static List<Test> selectAllByEntity(SqlSession session){ //如果不想使用实体类,查询结果可以使用List<Map<String, Object>>,类型需要和mapper文件中一致 List<Test> list = session.selectList("TestMapper.selectAllByEntity"); session.commit(); return list; } }
package com.chenwc; import com.chenwc.dao.TestDao; import com.chenwc.entity.Test; import com.chenwc.util.MybatisSessionUtil; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; /** * 测试 * @author chenwc */ public class Main { private static final Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args){ SqlSession session = MybatisSessionUtil.getSession(); if (null == session){ return; } //Test data = TestDao.getById("360881597623000", session); Test data2 = TestDao.getByIdParameterByMap("360881597623000", session); int count = TestDao.countById("360881597666500", session); //List<Map<String, Object>> list = TestDao.selectAll(session); //List<Test> list2 = TestDao.selectAllByEntity(session); log.info(String.valueOf(count)); //log.info(data.getId()); log.info(data2.getUuid()); //log.info(list.toString()); try { session.clearCache(); session.close(); }catch (Exception e){ e.printStackTrace(); } } }
log4j.rootLogger=info,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %-5p %-5L --- [%-5t] %-10c : %m %n