Article From:https://www.cnblogs.com/huanzi-qch/p/9970545.html

  Preface

  jpaORM mapping framework, more details, please stamp: apring-data-jpa official website: http://spring.io/projects/spring-data-jpa, here is just a record of project implementation.

 

  engineering structure

 

  Code writing

  mavenLeading bag

        <!--Adding spring data-jpa dependencies-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--Adding MySQL Driver Dependencies-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--lombokPlug-in unit-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

 

  applicaction.yml

#Note: When you add value values to the YML file, you need to add a space before valueConfiguration of # 2.0.0 is switched to servlet. path instead of "-"
server:
  port: 10086 #Port number
  servlet:
    context-path: /springboot #Access root path

spring:
    thymeleaf:
      cache: false  #Close page caching
      prefix: classpath:/view/  #thymeleafAccess root path
      mode: LEGACYHTML5

    datasource: #Database correlation
      url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver

    jpa:
      show-sql: true

    mvc:
      date-format: yyyy-MM-dd HH:mm:ss #mvcFormat the date when receiving parameters

    jackson:
      date-format: yyyy-MM-dd HH:mm:ss #jacksonFormat the date parameters for the response back
      time-zone: GMT+8

 

  Entity classes and table data

  tb_user

  tb_description

 

/**
 * User class*/
@Entity
@Table(name = "tb_user")
@Data
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY) //IDENTITY Self increment
    private Integer id;

    @Column(name = "username")//Name the same or hump identifier (mapping with database underlines) without writing
    private String username;

    private String password;

    private Date created;

    private String descriptionId;

    @OneToOne
    @JoinColumn(name = "descriptionId",referencedColumnName = "id", insertable = false, updatable = false)
    @NotFound(action= NotFoundAction.IGNORE)
    //User descriptioninformation
    private Description description;
}
/**
 * User Description Class*/
@Entity
@Table(name = "tb_description")
@Data
public class Description implements Serializable {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY) //IDENTITY Self increment
    private Integer id;

    private String userId;

    private String description;
}

 

   UserController

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getAllUser")
    public ModelAndView getAllUser(){
        Result result=userService.getAllUser();
        ModelAndView mv=new ModelAndView();
        mv.addObject("userList",result.getData());
        mv.setViewName("index.html");
        return mv;
    }

    @RequestMapping("page")
    public Result<PageInfo<User>> page(User entity, PageCondition pageCondition) {
        return userService.page(entity,pageCondition);
    }

    @RequestMapping("list")
    public Result<List<User>> list(User entity) {
        return userService.list(entity);
    }

    @RequestMapping("get/{id}")
    public Result<User> get(@PathVariable("id") Integer id) {
        return userService.get(id);
    }

    @RequestMapping("save")
    public Result<User> save(User entity) {
        return userService.save(entity);
    }

    @RequestMapping("delete/{id}")
    public Result<Integer> delete(@PathVariable("id") Integer id){
        return userService.delete(id);
    }
}

 

  UserService

public interface UserService{

    Result<PageInfo<User>> page(User entity, PageCondition pageCondition);

    Result<List<User>> list(User entity);

    Result<User> get(Integer id);

    Result<User> save(User entity);

    Result<Integer> delete(Integer id);

    Result getAllUser();
}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Result<PageInfo<User>> page(User entity ,PageCondition pageCondition) {
        Page<User> page = userRepository.findAll(Example.of(CopyUtil.copy(entity, User.class)), pageCondition.getPageable());
        int records = (int) page.getTotalElements();
        int pageSize = page.getSize();
        int total = records % pageSize == 0 ? records / pageSize : records / pageSize + 1;
        PageInfo<User> pageInfo = new PageInfo<>();
        pageInfo.setPage(page.getNumber() + 1);//Page number
        pageInfo.setPageSize(pageSize);//Page size
        pageInfo.setRows(page.getContent());//Paging results
        pageInfo.setRecords(records);//Total number of records
        pageInfo.setTotal(total);//PageCount
        return Result.of(pageInfo);
    }

    @Override
    public Result<List<User>> list(User entity) {
        List<User> entityList = userRepository.findAll(Example.of(entity));
        return Result.of(entityList);
    }

    @Override
    public Result<User> get(Integer id) {
        Optional<User> optionalE = userRepository.findById(id);
        if (!optionalE.isPresent()) {
            throw new RuntimeException("IDNon-existent! ");
        }
        return Result.of(optionalE.get());
    }

    @Override
    public Result<User> save(User entity) {
        User user = userRepository.save(entity);
        return Result.of(user);
    }

    @Override
    public Result<Integer> delete(Integer id) {
        userRepository.deleteById(id);
        return Result.of(id);
    }

    @Override
    public Result getAllUser() {
        List<User> userList = userRepository.getAllUser();
        if(userList != null && userList.size()>0){
            return Result.of(userList);
        }else {
            return Result.of(userList,false,"Acquisition failure! ");
        }
    }
}

 

  UserRepository

public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {

    @Query(value = "from User") //HQL
//    @Query(value = "select * from tb_user",nativeQuery = true)//Native SQL
    List<User> getAllUser();

}

 

  Effect

  getInterface

  http://localhost:10086/springboot/user/get/1

 

  listInterface

  http://localhost:10086/springboot/user/list

   http://localhost:10086/springboot/user/list?username=Zhang San

   

  pageInterface

  http://localhost:10086/springboot/user/page?page=1&rows=10

   http://localhost:10086/springboot/user/page?page=1&rows=10&username=Zhang San

 

  saveInterface (insert and update)

  No ID or ID does not exist. For insertion, http://localhost:10086/springboot/user/save?Username=Zhang Mazi& password=123

  idIf it exists, it is updated, http://localhost:10086/springboot/user/save?Id=1& username=Zhangsan 1& password=666.

  deleteInterface

  http://localhost:10086/springboot/user/delete/6

 

  Customizing Dao Layer Method

  http://localhost:10086/springboot/user/getAllUser

  Epilogue

   JPAFucking great!

Leave a Reply

Your email address will not be published. Required fields are marked *