Spring boot笔记4

 整合Spring Data JPA

1. 创建Maven工程

cnn-info(打jar包),在pom.xml中进行如下配置

org.springframework.boot

spring-boot-starter-parent

1.4.4.RELEASE

org.springframework.boot

spring-boot-starter-web

1.4.4.RELEASE

org.springframework.boot

spring-boot-devtools

1.4.4.RELEASE

org.springframework.boot

spring-boot-starter-data-jpa

1.4.4.RELEASE

mysql

mysql-connector-java

5.1.6


2. 加入Spring-Boot配置文件

在src/main/resources 下添加application.properties 配置文件,内容如下:

#DB Configuration:

spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test

spring.datasource.username=root

spring.datasource.password=root


#JPA Configuration:

spring.jpa.database=MySQL

spring.jpa.show-sql=true

spring.jpa.generate-ddl=true

spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy


3. 创建实体类

import javax.persistence.Entity;

import javax.persistence.Id;


@Entity

public class User {

@Id

private Long id;

private String userName;

private String password;

private String name;


//添加 get 和set 方法

}


4. 创建DAO接口

import org.springframework.data.jpa.repository.JpaRepository;

import cn.cnn.info.pojo.User;


public interface UserDao extends JpaRepository {

}


5. 创建业务逻辑接口

import java.util.List;

import cn.cnn.info.pojo.User;


public interface UserService {

List findAll();

}


6. 创建业务逻辑实现类

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import cn.cnn.info.dao.UserDao;

import cn.cnn.info.pojo.User;

import cn.cnn.info.service.UserService;


@Service

public class UserServiceImpl implements UserService {


@Autowired

private UserDao userDao;


@Override

public List findAll() {

List list = this.userDao.findAll();

return list;

}

}


7. 创建Controller

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 cn.cnn.info.pojo.User;

import cn.cnn.info.service.UserService;


@RestController

@RequestMapping("user")

public class UserControlelr {


@Autowired

private UserService userService;


@RequestMapping("list")

public List queryUserAll() {

List list = this.userService.findAll();

return list;

}


}


8 创建引导类

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

你可能感兴趣的:(Spring boot笔记4)