tk.mybatis初探

据说tk.mybatis能够让我不写sql代码就可以所有单表操作问题,作为热爱偷懒的我,怎么能放过这种机会。talk is cheap, show me the code。赶紧搞个例子爽一把先。


例子使用springboot与MySQL搭建,因此需要准备必要的环境,我使用的是:

  • jdk 8
  • mysql 8
  • IDEA
  • maven

1、 pom文件


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.5.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.wmgroupId>
    <artifactId>laowangartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>laowangname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>tk.mybatisgroupId>
            <artifactId>mapper-spring-boot-starterartifactId>
            <version>2.1.5version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

    <repositories>
        <repository>
            <id>spring-milestonesid>
            <name>Spring Milestonesname>
            <url>https://repo.spring.io/milestoneurl>
        repository>
    repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestonesid>
            <name>Spring Milestonesname>
            <url>https://repo.spring.io/milestoneurl>
        pluginRepository>
    pluginRepositories>

project>

2、application.properties

server.port=8888
spring.datasource.url=jdbc:mysql://localhost:3306/laowang?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
#这里的debug是为了打印生成的sql语句到控制台,便于调试
logging.level.com.wm.laowang.dao=debug

3、entity层

package com.wm.laowang.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Id;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @Id //这里是用来标记数据库的主键
    private Long id;
    private String username;
    private String phone;
}

4、dao层

package com.wm.laowang.dao;

import com.wm.laowang.entity.User;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
@Repository
public interface UserDao extends Mapper<User> {
}

注意这里导入的包,这里用的是tk.mybatis.mapper.common.Mapper

这里没有写sql语句,一条也没有。

5、service层以及impl层

package com.wm.laowang.service;

import com.wm.laowang.entity.User;

public interface UserService {

    User getUser(long id);
}
import com.wm.laowang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Override
    public User getUser(long id) {
        return userDao.selectByPrimaryKey(id);
    }
}

6、web层

package com.wm.laowang.web;

import com.wm.laowang.entity.User;
import com.wm.laowang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("show/{id}")
    public String getUser(@PathVariable("id") long id){
        User user = userService.getUser(id);
        System.out.println(user);
        return "helloWorld";
    }
}

7、springboot程序启动入口

package com.wm.laowang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.wm.laowang.dao")
public class LaowangApplication {

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

}

这里要注意添加上@MapperScan(“com.wm.laowang.dao”)注解。
这样的话启动,然后发请求http://loclahost:8888/show/1就能在控制台看到输出结果了。当然了,数据库里没数据的话肯定不行。


遇到的一些问题

1、注入userDao失败,springboot无法启动。
Description:

Field userDao in com.wm.laowang.service.impl.UserServiceImpl required a bean of type 'com.wm.laowang.dao.UserDao' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)

咋一看好像是autowired的required属性问题,但并不是,设置为false能启动,但依然是没有这个bean的。问题的根源在于没有添加这个bean。所以,这里可以考虑在启动类的加上注解@MapperScan(“com.wm.laowang.dao”),括号里的value是你的dao的路径。

2、根据主键查询失败,总是为空。

  : ==>  Preparing: SELECT id,username,phone FROM user WHERE id = ? AND username = ? AND phone = ? 
  : ==> Parameters: 1(Long), 1(Long), 1(Long)
  : <==      Total: 0

这是由于未能识别主键导致的,主要有两个可能因素:

  • 实体类上没有添加@Id的注解,或者导入的包不是import javax.persistence.Id;
  • 主键的数据类型不是包装类型,而是基本数据类型,例如是用了long而不是Long

3、如何设置打印出生成的sql语句

设置application.properties的日志级别

logging.level.com.wm.laowang.dao=debug

com.wm,laowang.dao是项目中dao的包路径

你可能感兴趣的:(java,Spring,boot)