二:一个简单的 spring boot + gradle + mysql 项目
- 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’)
} 在resources 目录下的application.properties 下增加mysql 的连接信息
spring boot 默认是使用hibernate,在依赖org.springframework.boot:spring-boot-starter-data-jpa中有hibernate 的jar 包,包括spring-data-jpa、spring-orm、hibernate操作数据库
(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";
}
}
- 启动运行
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
发布评论