启动数据库
net start mysql80
进入数据库
mysql -u root -p
数据库创建
create database `product-428`;#创建数据库product-428
show databases;#查看创建详情
use `product-428`;#切换到product-428数据库
CREATE TABLE `customers`(
`id` BIGINT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL COMMENT "姓名",
`sex` VARCHAR(10) NOT NULL COMMENT "性别",
`addr` VARCHAR(255) NOT NULL COMMENT "地址",
`tell` BIGINT NOT NULL COMMENT "电话号码"
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4
创建springboot
项目 引入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
编写application.yaml
配置
server:
port: 8803
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/product-428?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Dao.xml
# 指定entity扫描包类让mybatis自定扫描到自定义的entity
type-aliases-package: com.df.entity
使用easycode
代码生成器自动
启动类扫描dao
@SpringBootApplication
@MapperScan("com.df.dao")
public class TestdemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestdemoApplication.class, args);
}
}
修改一下,将entity/customers使用@Data注解
@Data
public class Customers implements Serializable {
private static final long serialVersionUID = 825273281675616599L;
private Integer id;
private String name;
private String sex;
private Long tell;
private String addr;
}
然后mapper/CustomersDao.xml
文件,这里我们先使用测试insert
方法,所以修改一下这里
<!--新增所有列-->
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into `customers`(`name`, `sex`, `tell`, `addr`)
values (#{name}, #{sex}, #{tell}, #{addr})
</insert>
这里有个坑,就是表名这里,要注意得用反单引号
测试一下insert
@SpringBootTest
class CustomersServiceTest {
@Autowired
private CustomersService customersService;
@Test
void test() {
Customers customers = new Customers();
customers.setName("Xpt");
customers.setAddr("南京是浦口区江浦街道");
customers.setSex("male");
customers.setTell(13377265211L);
System.out.println(customers);
customersService.insert(customers);
System.out.println(customers);
}
}