1.导入相关依赖
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!--读取数据源信息-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverName}"></property>
<property name="username" value="${jdbc.username}"/>
<property name="url" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"></property>
</bean>
<!--扫描mapper所在的包-->
<bean id="mapperscan" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mc_74120.mapper"/>
</bean>
</beans>
6.测试是否成功
import com.mc_74120.mapper.AdminMapper;
import entity.Admin;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
@ContextConfiguration(locations ={"classpath:spring-mybatis.xml"})
@RunWith(SpringRunner.class)
public class Test01 {
@Autowired
private DataSource dataSource;
@Autowired
private AdminMapper adminMapper;
@Test
public void logger(){
//获取logger对象
Logger logger= LoggerFactory.getLogger(Test01.class);
//根据不同的日志打印级别打印日志
logger.debug("123");
}
@Test
public void insertAdmin(){
Admin admin=new Admin(null,"74120","123456","74120","1747481368@qq.com", null);
int count= adminMapper.insert(admin);
System.out.println(count);
}
@Test
public void test() throws SQLException {
Connection connection=dataSource.getConnection();
}
}
结果如图
原文:https://www.cnblogs.com/mc-74120/p/12812308.html