二十八、SpringBoot中使用JPA来访问数据库

            SpringBoot中使用JPA来访问数据库

1、实体类属性与表字段同名,实现序列化接口

package com.yang.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Enterprise implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }
}

2、实现JpaRepository接口

package com.yang.repo;

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

import com.yang.domain.Enterprise;


/**
 * 继承JpaRepository  接口,实现JPA
 * @author yang
 */
public interface EnterpriseRepo extends JpaRepository<Enterprise, Integer>{


}

3、注入接口

package com.yang.service;

import java.util.List;

import com.yang.domain.Enterprise;

public interface EnterpriseService {

    public void addEnterprise(Enterprise enterprise);
    public List<Enterprise> getEnterprise();
}

注入接口,并调用封装好的方法:

package com.yang.service.impl;

import java.util.List;

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

import com.yang.domain.Enterprise;
import com.yang.repo.EnterpriseRepo;
import com.yang.service.EnterpriseService;

@Service
public class EnterpriseServiceImpl implements EnterpriseService{

    @Autowired
    private EnterpriseRepo enterpriseRepo;

    @Override
    public void addEnterprise(Enterprise enterprise) {
        enterpriseRepo.save(enterprise);

    }

    @Override
    public List<Enterprise> getEnterprise() {
        return enterpriseRepo.findAll();
    }

}

猜你喜欢

转载自blog.csdn.net/newbie_907486852/article/details/81410104
今日推荐