1、项目结构
2、详细代码
数据库:
1、创建实体类bean
package com.itheima.domain;import java.io.Serializable;
import java.util.Date;/*** Created by Administrator on 2019/10/11.*/
public class User implements Serializable {private Integer id;private String username;private Date birthday;private String sex;private String address;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", birthday=" + birthday +", sex='" + sex + '\'' +", address='" + address + '\'' +'}';}
}
2、查找数据库中所有用户的Dao
package com.itheima.dao;import com.itheima.domain.User;import java.util.List;/*** Created by Administrator on 2019/10/11.* 用户持久层接口*/
public interface IUserDao {/*** 查询所有操作* @return*/List<User> findAll();
}
3、配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybatis的主配主文件-->
<configuration>
<!--配置环境-->
<environments default="mysql"><!--配置MySQL环境变量--><environment id="mysql"><!--配置事物的类型--><transactionManager type="JDBC"></transactionManager><!--配置数据源(连接池)--><dataSource type="POOLED"><!--配置链接数据库的四个基本信息--><property name="driver" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"></property><property name="username" value="root"></property><property name="password" value="123456"></property></dataSource></environment>
</environments><!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件--><mappers><mapper resource="com/itheima/dao/IUserDao.xml"/></mappers>
</configuration>
5、dao层对用的mapper映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.itheima.dao.IUserDao"><!--查询所有--><select id="findAll" resultType="com.itheima.domain.User">SELECT * FROM user;</select>
</mapper>
6、 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
7、test单元测试
package com.itheima.test;import com.itheima.dao.IUserDao;
import com.itheima.domain.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** Created by Administrator on 2019/10/12.*/
public class Mybatis {/*** 入门案例** @param args*/public static void main(String[] args) throws Exception {
// 1、 读取配置文件InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2、创建SqlSessionFactory工厂SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory =builder.build(in);
// 3、使用工厂生产SqlSession对象SqlSession session = factory.openSession();
// 4、使用SqlSession创建Dao接口的代理对象IUserDao userDao = session.getMapper(IUserDao.class);
// 5、使用代理对象执行方法List<User> users = userDao.findAll();for (User user :users){System.out.println(user);}
// 6、释放资源session.close();in.close();}
}
8、输出结果
"C:\Program Files\Java\jdk1.8.0_131\bin\java" -Didea.launcher.port=7533 "-Didea.launcher.bin.path=D:\IntelliJ IDEA 14.0.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_131\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;D:\IDEA项目\itheima_mybatis_day01_01\target\test-classes;D:\IDEA项目\itheima_mybatis_day01_01\target\classes;D:\ruanjian\meaven\apache-maven-3.6.2-bin\repository\org\mybatis\mybatis\3.4.5\mybatis-3.4.5.jar;D:\ruanjian\meaven\apache-maven-3.6.2-bin\repository\mysql\mysql-connector-java\5.1.6\mysql-connector-java-5.1.6.jar;D:\ruanjian\meaven\apache-maven-3.6.2-bin\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;D:\ruanjian\meaven\apache-maven-3.6.2-bin\repository\junit\junit\4.11\junit-4.11.jar;D:\ruanjian\meaven\apache-maven-3.6.2-bin\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\IntelliJ IDEA 14.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.itheima.test.Mybatis
2019-10-12 22:31:22,500 0 [ main] DEBUG ache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
2019-10-12 22:31:22,636 136 [ main] DEBUG source.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2019-10-12 22:31:22,637 137 [ main] DEBUG source.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2019-10-12 22:31:22,637 137 [ main] DEBUG source.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2019-10-12 22:31:22,637 137 [ main] DEBUG source.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2019-10-12 22:31:22,744 244 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2019-10-12 22:31:22,922 422 [ main] DEBUG source.pooled.PooledDataSource - Created connection 343965883.
2019-10-12 22:31:22,922 422 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@148080bb]
2019-10-12 22:31:22,924 424 [ main] DEBUG m.itheima.dao.IUserDao.findAll - ==> Preparing: SELECT * FROM user;
2019-10-12 22:31:22,963 463 [ main] DEBUG m.itheima.dao.IUserDao.findAll - ==> Parameters:
2019-10-12 22:31:22,994 494 [ main] DEBUG m.itheima.dao.IUserDao.findAll - <== Total: 6
User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京'}
User{id=42, username='小二王', birthday=Fri Mar 02 15:09:37 CST 2018, sex='女', address='北京金燕龙'}
User{id=43, username='小二王', birthday=Sun Mar 04 11:34:34 CST 2018, sex='女', address='北京金燕龙'}
User{id=45, username='传智播客', birthday=Sun Mar 04 12:04:06 CST 2018, sex='男', address='北京金燕龙'}
User{id=46, username='老王', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', address='北京'}
User{id=48, username='小马宝莉', birthday=Thu Mar 08 11:44:00 CST 2018, sex='女', address='北京修正'}
2019-10-12 22:31:22,997 497 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@148080bb]
2019-10-12 22:31:22,998 498 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@148080bb]
2019-10-12 22:31:22,998 498 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 343965883 to pool.Process finished with exit code 0
注意
该工程为Idea创建的Maven工程,目录结构与创建的纯Java工程不同,单元测试也不同,若为纯Java工程,请自行改造!
pom.xml
<?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.itheima</groupId><artifactId>itheima_mybatis_day01_01</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.11</version></dependency></dependencies></project>