之前写的程序可能有一些不规范的地方,所以这里看着书重新卸了一遍.
代码清单:
- log4j.properties
log4j.rootLogger=DEBUG , stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
- User.java
package mybatis.entity;
/**
* 实体类
*/
public class User {
private int id;
private String name;
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;
}
}
- UserMapper.java
package mybatis.mapper;
import mybatis.entity.User;
public interface UserMapper {
public User getUser(Integer id);
public int deleteUser(Integer id);
public int insertUser(User user);
public int updateUser(User user);
}
- user.mapper.xml
<?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">
<!-- namespace属性要和一个接口的全限定名保持一致 -->
<mapper namespace="mybatis.mapper.UserMapper">
<!-- resultMap元素用于定义映射规则 -->
<resultMap type="mybatis.entity.User" id="UserMapper">
<id property="id" column="id" />
<result property="name" column="name" />
</resultMap>
<select id="getUser" resultMap="UserMapper">
select * from user where id = #{id}
</select>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
<insert id="insertUser" parameterType="mybatis.entity.User" useGeneratedKeys="true">
insert into user(id,name) values(#{id},#{name})
</insert>
<update id="updateUser" parameterType="mybatis.entity.User">
update user set name=#{name} where id = #{id}
</update>
</mapper>
- mybatis-cfg.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>
<typeAlias type="mybatis.entity.User" alias="user"/>
</typeAliases>
<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://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="user.mapper.xml" />
</mappers>
</configuration>
- SqlSessionFactoryUtils.java
package mybatis.util;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.IIOException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionFactoryUtils {
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactoryUtils() {
}
public static SqlSessionFactory getSqlSessionFactory() throws IOException {
synchronized (LOCK) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
String resourse = "mybatis.cfg.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resourse);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IIOException e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
public static SqlSession openSession() throws IOException {
if (sqlSessionFactory == null) {
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
- Test.java
package mybatis.test;
import java.io.IOException;
import javax.jws.soap.SOAPBinding.Use;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import mybatis.entity.User;
import mybatis.mapper.UserMapper;
import mybatis.util.MybatisUtil;
import mybatis.util.SqlSessionFactoryUtils;
public class Test {
public static void main(String[] args) throws IOException {
Logger logger = Logger.getLogger(Test.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUser(1);
logger.info(user.getName());
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
DEBUG 2019-11-17 16:28:28,478 org.apache.ibatis.logging.LogFactory: Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG 2019-11-17 16:28:28,948 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2019-11-17 16:28:28,948 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2019-11-17 16:28:28,948 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2019-11-17 16:28:28,948 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2019-11-17 16:28:29,370 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
DEBUG 2019-11-17 16:28:30,412 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 699780352.
DEBUG 2019-11-17 16:28:30,412 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@29b5cd00]
DEBUG 2019-11-17 16:28:30,416 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Preparing: select * from user where id = ?
DEBUG 2019-11-17 16:28:30,454 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 1(Integer)
DEBUG 2019-11-17 16:28:30,494 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <== Total: 1
INFO 2019-11-17 16:28:30,495 mybatis.test.Test: 张三
DEBUG 2019-11-17 16:28:30,495 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@29b5cd00]
DEBUG 2019-11-17 16:28:30,495 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@29b5cd00]
DEBUG 2019-11-17 16:28:30,496 org.apache.ibatis.datasource.pooled.PooledDataSource: Returned connection 699780352 to pool.