创建Mapper接口
package com.mapper;
import com.doMain.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MyMapper {
List<User> findAll();
void saveUser(User user);
}
创建mapper对应的配置文件
注意该配置文件需要和mapper接口的
<?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.mapper.MyMapper">
<!-- 配置查询所有操作 -->
<select id="findAll" resultType="com.doMain.User">
select * from tb_user
</select>
<insert id="saveUser" parameterType="com.doMain.User">
insert into tb_user (user_name,password,name,age,sex,birthday,note,created,updated)
values (#{userName},#{password},#{name},#{age},#{sex},#{birthday},#{note},#{created},#{updated})
</insert>
</mapper>
编写application.yml
加上如下配置:
注意这里填写mysql的驱动的时候不能使用com.mysql.jdbc.driver,不知道为什么会报错
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: root
mybatis:
type-aliases-package: com.doMain
mapper-locations: classpath:mapper/*.xml
在server层注入mapper并且调用方法
package com.service.Impl;
import com.doMain.User;
import com.mapper.MyMapper;
import com.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class ServiceImpl implements IService {
@Autowired
MyMapper myMapper;
@Override
public List<User> findAll() {
List<User> all = myMapper.findAll();
System.out.println(all);
/* for (User user : all) {
System.out.println(user);
}*/
return null;
}
@Override
@Transactional
public void saveUser(User user) {
myMapper.saveUser(user);
System.out.println("serivce保存了用户");
}
}