pom.xml中的坐标
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency>
log4j.properties
log4j.rootLogger=DEBUG, stdout # SqlMap logging configuration... log4j.logger.com.ibatis=DEBUG log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=DEBUG log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=DEBUG log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=DEBUG log4j.logger.com.ibatis.common.util.StopWatch=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG # 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
mybatis-config.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.baizhi.dao"/> </typeAliases> <!-- 数据库环境设置 ,可以配置多个环境设置 属性 default:指定当前使用的数据库环境 --> <environments default="db1"> <!-- 一个数据库环境的设置 id 当前环境的唯一标识 --> <environment id="db1"> <!-- 事务控制机制 type: JDBC MANAGER 交给第三方软件处理事务 --> <transactionManager type="JDBC"></transactionManager> <!-- 连接池设置 type : POOLED 使用数据库连接池 UNPOOLED 不使用数据库连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/alex?useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <!-- 注册所有mapper.xml --> <!-- <mapper resource="com/baizhi/dao/EmpDaoMapper.xml"/> --> <!-- 自动扫描包,自动注册mapper.xml 要求 dao接口对应的xml文件,名字必须相同--> <package name="com.baizhi.dao"/> </mappers> </configuration>
MyBatiusUtil
package com.baizhi.util; 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 java.io.IOException; import java.io.Reader; public class MyBatisUtil { private static SqlSessionFactory ssf; static { try { //读取主配置文件 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); //创建sqlsessionfactory(sqlsession工厂) ssf = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { throw new RuntimeException(e); } } public static SqlSession getSqlSession() { //通过ssf获取sqlsession SqlSession sqlSession = null; sqlSession = ssf.openSession(); return sqlSession; } //先判断sqlsession不是空再关 public static void close(SqlSession sqlSession) { if(sqlSession!=null) { sqlSession.close(); } } }
以粮为纲全面发展