1.applicationContext.xml添加配置
<!--加载属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--mybatis交给spring来管理,所以他的配置写在下面 -->
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<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>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.pro.dao"/>
</bean>
2.连接数据库 jdbcproperties.xml
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/class8
jdbc.username=root
jdbc.password=12345678
3.添加实体类
package com.pro.domain;
public class Xx {
private Integer id;
private String content;
public Xx() {
}
public Xx(String content) {
this.content = content;
}
@Override
public String toString() {
return "Xx{" +
"id=" + id +
", content='" + content + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
4.添加XxDao接口
package com.pro.dao;
import com.pro.domain.Xx;
public interface XxDao {
public void insertXx(Xx xx);
}
5.xxDao.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.pro.dao.XxDao">
<insert id="insertXx" parameterType="xx">
insert into xx(content) values (#{content})
</insert>
</mapper>
6.XxService接口
package com.pro.service;
import com.pro.domain.Xx;
public interface XxService {
public void save(Xx xx);
}
7.XxServiceImpl
package com.pro.service;
import com.pro.dao.XxDao;
import com.pro.domain.Xx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class XxServiceImpl implements XxService {
@Autowired
private XxDao xxDao;
@Override
public void save(Xx xx) {
xxDao.insertXx(xx);
}
}
8.XxTest.java
import com.pro.domain.Xx;
import com.pro.service.XxService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class XxServiceTest {
@Autowired
private XxService xxService;
@Test
public void save() {
xxService.save(new Xx("nmnmnmnm"));
}
}
添加成功