springboot-mybatis 实现数据库操作
程序员文章站
2022-05-26 11:29:26
...
之前的项目是建立在使用已有的JPA接口操作数据库,我们这次不使用JPA的接口,自己设计数据库的连接和增删改查,并让操作能够界面化,废话不多说,先把项目结构发出来。
包名功能分析:
mapper包下面有PersonMapper和PersonMapper.xml两个文件,其中PersonMapper.xml 里面些sql语句,PersonMapper将PersonMapper.xml中的语句进行用。注意:PersonMapper是一个接口,只需声明方法,不用实现
nPerson包 这里用不到
other包 里面的PersonController是对方法进行映射和适配,在得到请求指令后,会在这个类中找对应的方法,进行操作。
Person包 这里的Person是实体类,数据库的名称要和类名一致。
service包 PersonController在使用方法时,会使用PersonService接口中的方法,而PersonServiceImpl类是实现PersonService接口中的方法。
整个结构的数据流程是:
- 从页面发来请求
- Controller得到请求,并调用PersonService中的方法
- PersonService的方法由PersonServiceImpl实现
- PersonServiceImpl 的方法会调用PersonMapper接口中的方法
- PersonMapper接口的方法会在xml文件中运行sql语句,进行数据库操作
我们把整个项目的逻辑整理清晰了之后,接下来编码就容易理解很多了
第一步、添加POM依赖
这里需要提的一点是<bulid>里的sources中的内容,在这个项目中我把xml文件放在了src/main/java/helloworld/mapper目录下,所以我在src/main/java中搜索**/*.xml文件。如果你的xml文件放在了src/main/resource下面的目录下的话,就把src/main/java里的东西放在src/main/resource下面
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- freemaker依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--jsp页面使用jstl标签-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
第二步、配置数据库信息
直接在aplication.properties中写入数据库的连接
spring.freemarker.cache = false
spring.thymeleaf.cache = false
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
mybatis.mapperLocations=classpath*:mapper/*.xml
mybatis.type-aliases-package=com.example.freemarker.Person;
default_encoding=UTF-8
locale=zh_CN
第三步、设计数据库表的实体类
这个项目中,我用Person这个实体类,只要这个类名在数据库中有,并且需要把表中的名称通过变量的形式声明,加入get(),set()方法,注意:Person()类的构造函数不能缺少
第四步,设计PersonMapper.xml文件
我们这里不使用JPA等封装好的文件,而是使用xml文件和mybatis整合进行数据库语句的使用
如果想使用模糊查询的话,可以看 这个 文章
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mappper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.helloworld.mapper.PersonMapper">
<insert id="saveUser" >
INSERT INTO person VALUES(#{id},#{name})
</insert>
<select id="seletemap" parameterType="int" resultType="hashMap">
SELECT * from person where id = #{id}
</select>
<select id="seleteperson" parameterType="int" resultType="com.example.helloworld.Person.Person">
SELECT * from person where id = #{id}
</select>
<select id="seletepername" parameterType="int" resultType="com.example.helloworld.Person.Person">
SELECT * from person where name = #{name}
</select>
<resultMap id="resultmap" type="com.example.helloworld.Person.Person"> <!-- resultType="Map"-->
<!-- select * from nperson-->
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<select id="seleteAll" resultType="com.example.helloworld.Person.Person" >
select * from person
</select>
<update id="modify" >
UPDATE person set name = #{name} where id=#{id}
</update>
<update id="modifyall" >
UPDATE person set id=#{id} ,name = #{name} where id=#{oid}
</update>
<delete id="dele" parameterType="int">
delete from person where id=#{id}
</delete>
</mapper>
第五步,完成了xml文件的配置,我们就一块吧PersonMapper接口一起完成
注意:xml文件的方法要对应接口中的方法,大小写不能错,xml文件中的namespace一定,一定,一定(重要的话说三遍)要和 PersonMapper接口的路径一致,
package com.example.helloworld.mapper;
import com.example.helloworld.Person.Person;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface PersonMapper {
public List<Person> seleteAll();
public Person seleteperson(Integer id);
public List<Person> seletepername(Integer name);
public void saveUser(Person person);
public void modify(Person person);
public void modifyall(Person person);
public void dele(Integer id);
}
第六步、PersonMapper接口实现了,那么我们要用PersonServiceImpl 调用接口方法,再让PersonService声明PersonServiceImpl中的方法名
注意:Service包下的类都要用@Service标签声明
package com.example.helloworld.service;
import com.example.helloworld.Person.Person;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
@Service
public interface PersonService {
public List<Person> selete();
public Person ServicefindById(Integer id);
public List<Person> ServicefindByName(Integer name);
public void deletePerson(Integer id);
public int save(Person person);
public void update(Person person);
public void updateall(Person person);
}
package com.example.helloworld.service;/*
* Created by ZHANG on 2018/7/26
*/
import com.example.helloworld.Person.Person;
import com.example.helloworld.mapper.PersonMapper;
import com.sun.xml.internal.xsom.impl.scd.Iterators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonMapper personMapper;
public List<Person> selete(){
List<Person> list = new ArrayList<>();
list = personMapper.seleteAll();
return list;
}
//通过ID查找
public Person ServicefindById(@RequestParam("id") Integer id) {
Person person = personMapper.seleteperson(id);
if (null != person) {
return person;
}
return null;
}
//通过name查找
public List<Person> ServicefindByName(@RequestParam("name") Integer name) {
List<Person> list = new ArrayList<>();
list = personMapper.seletepername(name);
return list;
}
//通过ID删除
public void deletePerson(@RequestParam("id") Integer id){
personMapper.dele(id);
}
//通过ID修改name
public void update(@RequestParam("Person") Person person){
personMapper.modify(person);
}
//修改id+name
public void updateall(@RequestParam("Person") Person person){
personMapper.modifyall(person);
}
//通过ID增加
public int save(Person person){
personMapper.saveUser(person);
if(personMapper.seleteperson(person.getId())!= null)
return 1;
return 0;
}
}
最后一步是PersonController 的实现
@Controller
public class PersonController {
private ModelAndView mv;
@Autowired
private PersonService personService;
//主页
@RequestMapping("/findAll")
public String ALL(Map<String,Object> res) {
List<Person> list = personService.selete();
List<Map<String,Integer>> listres = new ArrayList<>();
for(Person p:list){
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("id",p.getId());
map.put("name",p.getName());
listres.add(map);
}
res.put("listres",listres);
return "a";
}
//@ResponseBody
@GetMapping(value = "/findid")
public String find(@RequestParam("id") Integer id,Map<String,Object> res) {
Person person = personService.ServicefindById(id);
List<Map<String,Integer>> listres = new ArrayList<>();
if(null == person) {
res.put("error","提交方式错误");
return "a";
}
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("id", person.getId());
map.put("name", person.getName());
listres.add(map);
res.put("listres",listres);
return "a";
}
@RequestMapping(value = "/findname")
public String findname(@RequestParam("name") Integer name,Map<String,Object> res) {
if(name == null)
res.put("error","提交方式错误");
List<Person> list = personService.ServicefindByName(name);
res.put("findn",name);
List<Map<String,Integer>> listres = new ArrayList<>();
for(Person p:list){
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("id",p.getId());
map.put("name",p.getName());
listres.add(map);
}
res.put("listres",listres);
return "a";
}
@ResponseBody
@RequestMapping(value = "/del")
public String del(@RequestParam("delname") Integer id) {
if(id == null)
return "请输入数据";
if(personService.ServicefindById(id) == null)
return "id not found";
personService.deletePerson(id);
return "success delete";
}
@ResponseBody
@RequestMapping(value = "/saveone")
public String saveone(@RequestParam("id")Integer id,
@RequestParam("name")Integer name,
Map<String,Object> res) {
if(id == null || name == null) {
//res.put("error","提交方式错误");
return "提交方式错误";
}
if(personService.ServicefindById(id) != null)
return "id cannot build";
Person person = new Person(id,name);
personService.save(person);
return "success";
}
@ResponseBody
@RequestMapping(value = "/updateone")
public String update(@RequestParam("id")Integer id,
@RequestParam("name")Integer name){
if(id == null || name == null)
return "请输入数据";
if(personService.ServicefindById(id) == null)
return "id not found";
Person person = new Person(id,name);
personService.update(person);
return "success update";
}
//原主页
@RequestMapping("/aaa")
public ModelAndView insert(){
ModelAndView mv = new ModelAndView();
mv.setViewName("a");
return mv;
}
//修改页面
@RequestMapping("/updpage")
public ModelAndView updpage(@RequestParam("updid") Integer id,Map<String,Object> res){
ModelAndView mv = new ModelAndView();
res.put("id",id);
mv.setViewName("upd");
return mv;
}
//@ResponseBody
@RequestMapping("/tabledel")
public String deletemany(@RequestParam("delid") Integer id){
personService.deletePerson(id);
//return "delete this id success";
return "a";
}
@ResponseBody
@RequestMapping(value = "/updateall")
public String updateall(@RequestParam("id")Integer id,
@RequestParam("oldid")Integer oldid,
@RequestParam("name")Integer name){
if(id == null || name == null)
return "请输入数据";
List<Person> list = personService.selete();
List<Integer> idlist = new ArrayList<>();
for(Person p:list)
if(p.getId() != oldid)
idlist.add(p.getId());
Person person = new Person(id,name);
if(idlist.contains(id))
return "这个id已经使用了";
Person person1 = new Person(oldid,id,name);
personService.updateall(person1);
return "success update";
}
}
这样我们就实现了SPRINGBOOT和mybatis的整合,不过还有界面化的实现,留在下一篇实现吧。
下一篇: 数据结构 - 单链表 - C 语言