SpringBoot链接数据库(自用基础)

1、加入mysql依赖:


       
 <dependency>
     <groupId>com.mysql</groupId>
     <artifactId>mysql-connector-j</artifactId>
 </dependency>

   加入mybatis启动器依赖:
     
  <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>3.0.4</version>
  </dependency>

2、配置数据源:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8
spring.datasource.username=root
spring.datasource.password=root
   配置mybatis:( 配置为驼峰命名 映射 数据表下划线)
       
 mybatis.configuration.map-underscore-to-camel-case=true

   配置mapper.xml文件所在位置
       
 mybatis.mapper-locations=classpath:mapper/*.xml

3、创建接口文件:com.example.lesson04demo.dao.EmpMapper


   注意:如果不想标注@Mapper注解,则需要在主类上标注@MapperScan("com.example.lesson04demo.dao")
       
 @Mapper
 public interface EmpMapper
 {
   List<Emp> selectEmps();
   Emp selectById(Integer id);
   int insert(Emp emp);
   int deleteById(Integer id);
   int update(Emp emp);
  }


4、创建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.lesson04demo.dao.EmpMapper">
            <!--List<Emp> selectEmps();-->
            <select id="selectEmps" resultType="com.example.lesson04demo.entity.Emp">
                select * from emp
            </select>
            <!--Emp selectById(Integer id);-->
            <select id="selectById" resultType="com.example.lesson04demo.entity.Emp">
                select * from emp where id = #{id}
            </select>
            <!--int insert(Emp emp);-->
            <insert id="insert">
                insert into emp(name,age,job,salary,entry_date,manager_id,dept_id)
                values (#{name},#{age},#{job},#{salary},#{entryDate},#{managerId},#{deptId})
            </insert>
            <!--int deleteById(Integer id);-->
            <delete id="deleteById">
                delete from emp where id = #{id}
            </delete>
            <!--int update(Emp emp);-->
            <update id="update">
                update emp
                    set name=#{name},age=#{age},salary=#{salary},
                        entry_date=#{entryDate},manager_id=#{managerId},
                        dept_id=#{deptId},job=#{job}
                    where id = #{id}
            </update>
        </mapper>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值