1、导入依赖
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- MySQL驱动 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.24</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、xml配置版
(1)mapper(dao)
public interface UserMapper {
List<User> selectAllUser();
}
public class UserMapperImp2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectAllUser() {
return getSqlSession().getMapper(UserMapper.class).selectAllUser();
}
}
(2)pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private long id;
private String username;
private String password;
private long age;
private String sex;
private String email;
}
(3)jdbc、log4j配置
jdbc
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/MyBatis?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=1234567
log4j
#将Mybatis log4j运行级别调到DEBUG可以在控制台打印出Mybatis运行的sql语句
log4j.rootLogger=DEBUG,Console
### 把日志信息输出到控制台 ###
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=Sun: %m%n
#log4j.appender.Console.layout.ConversionPattern=data:%d{yyyy-MM-dd HH:mm:ss}%n
#log4j.logger.(写接口的全限定名,即对应于dao中的接口)可以打印出更详细的结果
#log4j.logger.dao.StudentDao=TRACE
(4)mybatis-config
需要设置类的别名和引入mapper.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>
<!-- <properties resource="jdbc.properties"/>-->
<!-- 引入log4j 配置-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 批量设置别名,会自动的将该包下的所有类定义了别名,别名就是其自身且不区分大小 -->
<typeAliases>
<typeAlias type="com.zhangxin.pojo.User" alias="user"/>
</typeAliases>
<!--引入映射文件-->
<mappers>
<!-- <mapper resource="mappers/UserMapper.xml"/>-->
<!-- 引入整个包的mapper.xml,需要目录结构目录名字,文件名和相关接口所在的包名一致-->
<package name="com.zhangxin.mapper"/>
</mappers>
</configuration>
(5)sping配置文件
需要注册SqlSessionFactory,SqlSessionFactory是创建SqlSession的工厂,它是个单个数据库映射关系经过编译后的内存镜像。
SqlSession可以通过getMapper()方法获得获取mapper,mapper接口可以映射到mapper.xml中写好的SQL语句。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 定义 sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定myBatis配置文件-->
<property name="configLocation" value="classpath:myBatis-config.xml"/>
</bean>
<bean id="userMapper2" class="com.zhangxin.mapper.UserMapperImp2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
(6)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">
<mapper namespace="com.zhangxin.mapper.UserMapper">
<select id="selectAllUser" resultType="com.zhangxin.pojo.User" >
select * from user;
</select>
</mapper>
(7)Test
public void test2()throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
// System.out.println(userMapper.selectAllUser());
userMapper.selectAllUser().forEach(user -> System.out.println(user));
}
3、纯注解版
(1)加入druid连接池依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
(3)dao层
之前的mapper+mapper.xm,用@Select等标签代替xml文件
public interface UserMapper {
@Select("select * from user")
List<User> selectAllUser();
}
(4)service层
service层调用dao层
public interface UserService {
List<User> selectAllUser();
}
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectAllUser() {
return userMapper.selectAllUser();
}
}
(5)config类(核心)
@PropertySource引入需要的资源文件,对应spring.xml:
< context:property-placeholder ignore-unresolvable=“true” location=“classpath:jdbc.properties”/>
@MapperScan扫描mapper包,对应mybatis-congig.xml:< package name=“com.zhangxin.mapper”/>
dataSource()方法和sqlSessionFactoryBean(DataSource dataSource)方法都是使用返回值的方式动态注入Bean。
@Configuration //声明该类是核心配置类
@ComponentScan("com.zhangxin") //开启spring注解扫描
@PropertySource("classpath:jdbc.properties") //引入properties文件
@MapperScan("com.zhangxin.dao") //MyBatis扫描dao接口
public class MyConfig {
//定义属性 为属性注入数据(数据的来源上面引入的db.properties文件)
@Value("${jdbc.driver}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//创建数据源返回数据源,Spring会自动调用该方法,并将该对象交给IOC容器管理
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driverClass);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
//创建SqlSessionFactoryBean对象,设置形参,Spring会自动去调用IOC容器中已有的数据源
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
(6)Test
public class MyTest {
@Test
public void test1()throws IOException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
UserServiceImp userService = context.getBean("userServiceImp", UserServiceImp.class);
List<User> users = userService.selectAllUser();
System.out.println(users);
}
}