目录
用idea创建了一个springboot架子(基于maven)
访问网站及配置数据源
数据源的配置在application.properties中,生成项目中有默认的,如下:
# 应用名称
spring.application.name=demo
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/blue?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=***
spring.datasource.password=***
web访问:需要@RestController和@RequestMapping
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private DataSource dataSource;
@RequestMapping("/dataSource")
public String testDataSource(){
System.out.println("数据源类型是:" + dataSource.getClass().getName());
return "OK";
}
}
在浏览器中输入:
结果:
@Transactional注解
@Transactional用来标识在类或类中的方法上。
标识在类上代表此类中所有非静态公共方法将应用数据库事务。
标识在方法上代表此方法将应用数据库事务;
@Transactional注解还定义了事务的隔离级别和传播行为,异常类型的配置,这些配置定义了事务如何执行,具有哪些特征
事务的隔离级别
DEFAUTL 值为-1,不执行事务
READ_UNCOMMITTED 值为1,未提交读,会产生脏读
READ_COMMITTED 值为2,读写提交,会产生不可重复读
PEATABLE_READ 值为4,可重复读,会产生幻读
SERIALIZABLE 值为8,串行化,最高级别,避免以上所有问题
例如:
package com.example.demo.service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
public class DepartmentService {
@Transactional(rollbackFor = java.lang.Exception.class,
isolation = Isolation.READ_COMMITTED,timeout = 1)
public int saveDepartment(){
return 0;
}
}
在psvm中要有EnableTransactionManagement
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//@SpringBootApplication
@SpringBootApplication
@EnableTransactionManagement
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
注意:这个注解和org.springframework的spring-tx有关,要引入
多文件配置
参考这篇
文件目录:
在application.properties要加入
spring.profiles.active=dev
application-dev.yml:(修改了端口号)
server:
port: 8912
结果:
使用了覆盖原有的配置的dev作为设置
springboot整合mybatis
注解方式
属性配置文件
#配置mybatis属性
mybatis.type-aliases-package=com.example.demo
方法的接口:
package com.example.demo.mappers;
import com.example.demo.domin.Department;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface DepartmentMapper {
@Select("select * from department")
List<Department> findAll();
}
Service层
package com.example.demo.service;
import com.example.demo.domin.Department;
import com.example.demo.mappers.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class DepartmentServiceImp implements DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
@Transactional(rollbackFor = java.lang.Exception.class,
isolation = Isolation.READ_COMMITTED,timeout = 1)
public int saveDepartment(){
return 0;
}
@Override
public List<Department> findAll() {
return departmentMapper.findAll();
}
}
Controller层:
package com.example.demo.controller;
import com.example.demo.domin.Department;
import com.example.demo.service.DepartmentServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/test")
public class DepartmentController {
@Autowired
private DepartmentServiceImp departmentServiceImp;
@RequestMapping("/findAll")
public String findAll(){
List<Department> departmentList = departmentServiceImp.findAll();
System.out.println(departmentList.size());
return "ok";
}
}
来访问一下:
结果略
一些注意的坑:
遇到:
这里的情况
需要在启动文件下加上
@EnableTransactionManagement(proxyTargetClass = true)
还有,配置数据库连接地址,是spring.datasource.jdbc-url,如果有问题,可能是写成了spring.datasource.url
最后,有一下错误,
java.sql.SQLException: 不支持的字符集 (在类路径中添加 orai18n.jar): ZHS16GBK
根据这篇文章来搞:
这篇文章
根据xml文件配置
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.example.demo.domin.Emp">
<select id="findEmp" resultType="emp" statementType="PREPARED">
select * from emp
</select>
</mapper>
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//@SpringBootApplication
@SpringBootApplication
//@EnableTransactionManagement
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan(value = {
"com.example.demo.mappers","com.example.demo.*.mappers"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.example.demo.mappers;
import com.example.demo.domin.Department;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface DepartmentMapper {
@Select("select * from department")
List<Department> findAll();
}
package com.example.demo.emp.service;
import com.example.demo.domin.Emp;
import com.example.demo.emp.mappers.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmpServiceImp implements EmpService{
@Autowired
private EmployeeMapper employeeMapper;
@Override
public List<Emp> findEmp() {
return employeeMapper.findEmp();
}
}
package com.example.demo.emp.Controller;
import com.example.demo.domin.Emp;
import com.example.demo.emp.service.EmpService;
import com.example.demo.emp.service.EmpServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/emp")
public class EmpController {
@Autowired
private EmpService empServiceImp;
@RequestMapping("/findEmp")
public ModelAndView findEmp(){
List<Emp> list = empServiceImp.findEmp();
System.out.println(list.size());
ModelAndView view = new ModelAndView("com/example/demo/page/index.jsp");
return view;
}
}
MyBatis Plus
简称MP,是myBatis的一个功能增强组件,唯一目的简化sql代码编写,提高效率,提供更多可以选择的简便操作数据API,它不对myBatis做任何更改,springboot提供了对MP的方便整合
配置:在pow加入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>mybatis-plus-latest-version</version>
</dependency>
配置lombok
配置lombok后,可以在类中不用生成set和get方法,以及一些其它方法
pow.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
建立Mapper(之前用了这个Mapper写了findAll方法,这里的findAll与示例无关)
package com.example.demo.mappers;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.domin.Department;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
public interface DepartmentMapper extends BaseMapper<Department> {
@Select("select * from department")
List<Department> findAll();
}
查询方法
在建立了Mapper,这个Mapper接口继承了BaseMapper,可以免费使用里面的方法,而不用写select语句了
DepartmentService
@Autowired
private DepartmentMapper departmentMapper;
@Override
public List<Department> queryDepList(){
return departmentMapper.selectList(null);
}
Controller
@RequestMapping("/findAll2")
public String queryDep(){
List<Department> departmentList = departmentServiceImp.queryDepList();
System.out.println(departmentList.size());
departmentList.forEach(System.out::println);
return "ook";
}
结果:
删除
domin
注意,要用@TableId注解主键,不然不会根据主键删除成功
package com.example.demo.domin;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.util.Date;
@Data(staticConstructor = "newInstance")
public class Department {
@TableId(value = "ID")
private String id;
private String name;
private String code;
private Date newdate;
private String descs;
}
service层
@Autowired
private DepartmentMapper departmentMapper;
@Override
public int deleteById(String id) {
return departmentMapper.deleteById(id);
}
controller层
@RequestMapping("/delete")
public String deleteDep(){
System.out.println(departmentServiceImp.deleteById("depid8"));
departmentServiceImp.queryDepList().forEach(System.out::println);
return "deleteOK";
}
插入
使用静态构造方法:
domin同上
package com.example.demo.domin;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.util.Date;
@Data(staticConstructor = "newInstance")
public class Department {
@TableId(value = "ID")
private String id;
private String name;
private String code;
private Date newdate;
private String descs;
}
service(节选,下同)
@Override
public int insertDep(Department department) {
return departmentMapper.insert(department);
}
controller
注意,这里用了构造方法来创建实例,这是设置好的
@RequestMapping("/insert")
public int insertDep(){
Department department = Department.newInstance();
department.setId("DEPID1009");
department.setCode("7788");
department.setName("卡卡部");
department.setNewdate(new Date());
department.setDescs("案例");
return departmentServiceImp.insertDep(department);
}
结果:数据库插入一条数据
查询一条记录(根据id)
@Override
public Department selectById(String id) {
return departmentMapper.selectById(id);
}
查询返回Map
新建xml文件,注意namespace
<?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.example.demo.mappers.DepartmentMapper">
<select id="findDepMap" resultType="map">
select id,name,newdate from department
</select>
</mapper>
DepartmentMapper.java
package com.example.demo.mappers;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.domin.Department;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Mapper
public interface DepartmentMapper extends BaseMapper<Department> {
@Select("select * from department")
List<Department> findAll();
public List<Map<String,Object>> findDepMap();//与xml一致
}
DepartmentServiceImp.java
@Override
public List<Map<String, Object>> findDepMap() {
List<Map<String,Object>> list = departmentMapper.findDepMap();
System.out.println("查询的总语句数:"+list.size());
return list;
}
Controller.java
@RequestMapping("sm")
public String selectMap(){
List<Map<String,Object>> list = departmentServiceImp.findDepMap();
list.get(0).keySet().forEach(System.out::println);//全是大写
return "yes";
}
结果:
可以看到,键名都是大写