使用micronaut创建基于maven的web工程集成jpa实现crud

1.使用mn命令创建工程

打开命令行窗口进入需要创建工程的目录,执行如下命令

mn create-app -b maven --jdk 8 --lang java --features data-jpa,mysql,properties com.test.web.web

创建完成打开工程目录可以看到如下文件列表,此时我们的maven工程就创建好了

2.编译

在根目录用maven正常编译,或idea中编译即可,Application为启动类

3.配置修改

如下修改数据库连接配置与jpa配置

4.创建Entity与Repository

@Entity
@Table(name = "test_user_t")
public class TestUserEntiry implements Serializable {
          
   

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "username")
    private String username;

    @Column(name = "age")
    private int age;

    @Column(name = "create_time")
    private Long createTime;
}

CrudRepository帮我们封装了一些通用方法,直接继承CrudRepository就行

@Repository
public interface TestUserRepository extends CrudRepository<TestUserEntiry, Long> {
          
   

}

5.创建测试Controller

@Controller("/test")
public class TestUserController {
          
   

    private final TestUserRepository testUserRepository;

    public TestUserController(TestUserRepository testUserRepository) {
          
   
        this.testUserRepository = testUserRepository;
    }

    @Get("/findAll")
    public Iterable<TestUserEntiry> test() {
          
   
        return testUserRepository.findAll();
    }

    @Post("/add")
    public boolean addUser(@Body JsonObject json) {
          
   
        testUserRepository.save(new TestUserEntiry(json.get("username").getStringValue(), json.get("age").getIntValue()));
        return true;
    }
}

6.测试

运行Application,可以看到如下打印信息 打开浏览器,输入http://localhost:8091/test/findAll即可查询数据 在resources目录新建views目录,然后新建index.html,引入jqyery添加保存代码,如下 然后浏览器输入http://localhost:8091/views进入index.html页面插入数据之后再查询 代码已上传gitee,

经验分享 程序员 微信小程序 职场和发展