sprigboot整合Mybatis

步骤:

1.配置数据源

spring:
  datasource:
    username: root
    password: 151630
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

2.新建数据库表

CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

3.实体类

public class Department {
    private Integer id;
    private String departmentName;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", departmentName='" + departmentName + '\'' +
                '}';
    }
}


public class Employee {
    private  Integer id;
    private  String lastName;
    private  String email;
    private  Integer gender;
    private  Integer dId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", dId=" + dId +
                '}';
    }
}

注解版Mybatis

映射类

//指定这是一个操作数据库的Mapper
@Mapper
public interface DepartmentMapper {
    @Select("select * from  department where id=#{id}")
    Department getById(Integer id);

    @Delete("delete from department where id=#{id}")
    int delete(Integer id);
    
    //获取新增数据主键
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName)values(#{departmentName})")
    int insert(Department department);
    
    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    int update(Department department);
}

Controller类

@RestController
public class dept {
    @Autowired
    DepartmentMapper departmentMapper;
    @RequestMapping("/dept/{id}")
    public Department department(@PathVariable("id") Integer id){
        return  departmentMapper.getById(id);
    }

    @RequestMapping("/insert")
    public  Department department(Department department){
         departmentMapper.insert(department);
         return department;
    }
    @RequestMapping("/delete/{id}")
    public  Department delete(@PathVariable("id") Integer id)
    {
        Department department = departmentMapper.getById(id);
        departmentMapper.delete(id);
         return  department;
    }
    @RequestMapping("/update/{id}")
    public Department update(Department department,@PathVariable("id") Integer id)
    {
        department = departmentMapper.getById(id);
        department.setDepartmentName("人事部");
        departmentMapper.update(department);
        return  department;
    }
}

配置文件版

EmployeeMapper.xml

<mapper namespace="com.zlb.springbootmybatis.mapper.EmployeeMapper">

    <select id="getById" resultType="com.zlb.springbootmybatis.admin.Employee">
        select * from mybatis.employee where id=#{id}
    </select>

    <insert id="insert" >
        insert into mybatis.employee(lastName, email, gender, d_id)
        values(#{lastName},#{email},#{gender},#{dId})
    </insert>

</mapper>

myabtis配置

//第一种方式
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    #开启驼峰式规则
    map-underscore-to-camel-case: true

//第二种方式
@org.springframework.context.annotation.Configuration
public class MybatisConfig {
	 //导入数据源
	 @ConfigurationProperties(prefix = "spring.datasource")
    @Bean(name = "dataSource")
    public DataSource druid(){
        return new DruidDataSource();
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        PathMatchingResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
       sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));   sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject();
    }
}

测试:

 @Autowired
    EmployeeMapper employeeMapper;
    @RequestMapping("/select/{id}")
    public Employee select(@PathVariable("id") Integer id){
        Employee employee = employeeMapper.getById(id);
        return  employee;
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值