Mybatis-plus实践(一)

1、打开idea,新建spring boot项目,Developer Tools勾选Lombok,Web勾选Spring Web和Spring Session。

2、在pom.xml文件中加入Mybatis-plus依赖,并交给Maven自动下载。

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>
#以下解决连接数据库时com.mysql.cj.jdbc.Driver报错问题
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>8.0.21</scope>
</dependency>

3、打开application.properties文件,连接Mysql数据库。

server.port=8888
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/bingo
spring.datasource.username=root
spring.datasource.password=123456
#解决带_ 的时候获取不到值,自动驼峰转换关闭
mybatis-plus.configuration.map-underscore-to-camel-case=false

4、在“src-main-java-com-example”目录下新建以下包,搭建项目结构。

(1)controller:承上启下,前端请求的方法、参数等,把service层的业务逻辑注入;

(2)service:后端的业务逻辑,定义一些接口及接口的实现

(3)dto:POJO理论模型,用于对象间的传输的类

(4)mapper:定义了数据库的一些接口,和数据库打交道

(5)entity:与数据库中表相对应的实体对象

(6)config:配置相关的类

5、在mysql数据库中新建user表,添加id、name、password属性。

6、在entity包下新建User类

@Data
@TableName(value = "user")
public class User {
    @TableId
    private Long id;
    @TableField(value = "name")
    private String userName;
    private String password;
}

7、在mapper包下新建UserMapper接口

@Mapper
@Component
public interface UserMapper extends BaseMapper<User> {
}

8、在service包下新建UserService接口,在service包下新建新建impl包存放接口的实现,在impl下新建UserServiceImpl类

public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

9、在dto包下新建UserDTO类

@Data
public class UserDTO {
    private String userName;
    private String password;
}

10、在controller包下新建UserController类

@Controller
public class UserController {
    //依赖注入
    @Autowired
    private UserService userService;

    @PostMapping(value = "login")
    @ResponseBody
    public boolean userLogin(@RequestBody UserDTO userDTO) {
        User user = new User();
        //浅copy
        BeanUtils.copyProperties(userDTO,user);
        return userService.save(user);
    }
}

11、在启动类上方加上以下标签

@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
@MapperScan("com.example.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

12、运行程序,打开Postman测试是否连接成功

打开数据库user表中新增了一条数据,说明数据传输成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值