wwwzgy

全部源码请见https://gitee.com/elite216/MybatisSample/tree/master

1、创建一个Spring boot项目,在pom.xml文件中添加Mybatis和Ucanaccess两个依赖。

    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
           <version>5.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>

2、创建application.properties文件,写入access数据库的路径、数据库打开密码以及数据库驱动(ucanaccess)。

spring.datasource.driver-class-name = net.ucanaccess.jdbc.UcanaccessDriver
spring.datasource.url = jdbc:ucanaccess://D:/mybatis/test.mdb;openExclusive=false;ignoreCase
spring.datasource.password = 123456

3、作为简单示例,数据库中设置一个user表,里面两个字段ID和username,均为字符。

4、创建数据表对应的持久化实体UserEntity类:

package com;
public class UserEntity {
    private String ID;
    private String username;
    public String getID() {
        return ID;
    }
    public void setID(String iD) {
        ID = iD;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }    
}

5、创建一个数据访问接口Repository:

package com;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface Repository {
    @Select("select * from [user]")
    public List <UserEntity> findAll();
}

6、创建一个服务类UserService:

package com;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @Autowired Repository rpt;
    public List<UserEntity> findAll(){
    return rpt.findAll();
 }
}

7、创建一个控制类TestController:

package com.test;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.UserService;
import com.UserEntity;
@RestController
public class TestController {
    @Autowired UserService us;
    @RequestMapping("/helloword")
    public List<UserEntity> hello(){
        return us.findAll();
    }
}

8、主程序入口增加@MapperScan注解:

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

@SpringBootApplication
@MapperScan(basePackages= {"com"})
public class MybatisTest {
    public static void main(String [] args) {
        SpringApplication.run(MybatisTest.class, args);
    }
}

所有文件结构如下图:

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-03-05
  • 2021-08-18
  • 2021-08-01
  • 2022-12-23
  • 2021-08-21
  • 2021-04-21
猜你喜欢
  • 2021-04-17
  • 2022-12-23
  • 2021-09-19
  • 2021-12-13
  • 2022-12-23
  • 2021-11-19
  • 2021-10-28
相关资源
相似解决方案