spring boot + gradle + mysql

编程知识 更新时间:2023-04-05 04:39:34

二:一个简单的 spring boot + gradle + mysql 项目

  1. gradle 中的依赖
    dependencies {
    compile(‘org.springframework.boot:spring-boot-starter-aop’)
    compile(‘org.springframework.boot:spring-boot-starter-data-jpa’)
    compile(‘org.springframework.boot:spring-boot-starter-thymeleaf’)
    compile(‘org.springframework.boot:spring-boot-starter-web’)
    runtime(‘mysql:mysql-connector-java’)
    testCompile(‘org.springframework.boot:spring-boot-starter-test’)
    }
  2. 在resources 目录下的application.properties 下增加mysql 的连接信息

    spring boot 默认是使用hibernate,在依赖org.springframework.boot:spring-boot-starter-data-jpa中有hibernate 的jar 包,包括spring-data-jpa、spring-orm、hibernate

  3. 操作数据库
    (1) entity

    (2) dao(操作数据库)

     @Repository
public interface UserRepositoty extends JpaRepository<User,Long> {
    @Query("select t from User  t where t.name = :name")
    User findByUserName(@Param("name") String name);
}

(3) service

    @Service
public class UserService {
    @Autowired
    private UserRepositoty userRepositoty;
    public User findUserByName(String name) {
        User user = null;
        try {
            user = userRepositoty.findByUserName(name);
        } catch (Exception e) {
        }
        return user;
    }
}

(4) controller

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/show")
    @ResponseBody
    public String show(@RequestParam(value = "name") String name) {
        User user = userService.findUserByName(name);
        if (null != user)
            return user.getId() + " & " + user.getName() + " & " + user.getPassword();
        else return "null";
    }
}
  1. 启动运行
    gradle build & java -jar build/lib/**.jar
    localhost:8080/user/show?name=*
    浏览器中显示查询到的内容—成功

本来是打算用oracle 数据库的,但是由于 maven 的仓库中没有oracle 的连接jar 包,需要本地引入,为了方便,就用了mysql 数据库。

对于hibernate 的操作不熟悉,同时相比较hibernate 更喜欢用 mybatis,下一步改造成mybatis。

更多推荐

spring boot + gradle + mysql

本文发布于:2023-04-05 04:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/6ea0f8a09c139cfd2947a2e787928434.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:boot   spring   mysql   gradle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 44818文章数
  • 14阅读数
  • 0评论数