springBoot+Jpa(hibernate)数据库基本操作

Jpa是什么?

JPA是一套规范,不是一套产品,那么像Hibernate,TopLink,JDO他们是一套产品,如果说这些产品实现了这个JPA规范,那么我们就可以叫他们为JPA的实现产品。

Spring-data-jpa依赖于Hibernate,具体的示例如下:

项目配置

在pom.xml中添加相关依赖,加入内容如下:



org.springframework.boot
spring-boot-starter-data-jpa

在application.xml中配置,数据库连接信息如下:

server.port=8081
spring.datasource.url = jdbc:mysql://localhost:3306/student?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query输入sql语句
spring.jpa.show-sql = true 
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

注:spring.jpa.show-sql =true 是在控制台输入sql语句

       对spring.jpa.hibernate.ddl-auto 这个属性,主要作用 是:自动创建、更新、验证数据表结构,该参数的几种配置如下:

  • create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
  • create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
  • update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
  • validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
创建实体bean如下:
@Entity
@Table(name = "t_bank_account")
public class BankAccount extends JpaRepositoriesAutoConfiguration{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String cardno;
    private String name;
    private Long id;
    private BigDecimal money;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCardno() {
        return cardno;
    }
    public void setCardno(String cardno) {
        this.cardno = cardno;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public BigDecimal getMoney() {
        return money;
    }
    public void setMoney(BigDecimal money) {
        this.money = money;
    }
}


创建服务访问数据库的DAO:

public interface BankAccountDao extends CrudRepository, Long> {

    //根据编号查询
    public BankAccount findById(Long id);


    @Query(value = "select * from t_bank_account where name like %?1%",nativeQuery = true)
    @Modifying
    public List findByNameLike(String name);//NotLike --- 等价于 SQL 中的 "not like",比如 findByNameNotLike(String name)
    public Page findAll(Pageable pageable);

    //联合查询数据
    @Query(value = "SELECT b.id,a.name as name,b.name,a.age,b.cardno,b.money from user a LEFT JOIN t_bank_account b on a.id=b.id and b.id=?1",nativeQuery = true)
    @Modifying
    public List findOrderById(Integer id);

    //源生sql插入
    @Query(value = "insert into t_bank_account(cardno,name,money) value(?1,?2,?3)",nativeQuery = true)
    @Modifying
    @Transactional
    public void insertBank_account(String cardNo, String name, BigDecimal money);

    //源生sql修改
    @Query(value = "update t_bank_account set name = ?2 where id=?1",nativeQuery = true)
    @Modifying
    @Transactional
    public  void updateOne(Long id,String name);

    //源生sql 删除
    @Query(value = "delete from t_bank_account where id = ?1",nativeQuery = true)
    @Modifying
    @Transactional
    public void deteteBankAccountById(Long id);
}

该类继承CrudRepository,通过查看CrudRepository接口的API文档,可以看到该接口本身实现了创建(save),更新(save),删除(delete),查询(findId,findAll)等基本的操作函数,因此我们在开发过程中,就没有必要在继续进行开发定义了

上面还有使用源生的sql进行查询,注意的是提交的时候@Trancational是必须要写的。

Controller控制台示例如下:


      

public class BankAccountController{

    @Resource
    BankAccountDao accountDao;

    @ApiOperation(value = "查找银行用户")
    @RequestMapping(value = "/findById" , method = RequestMethod.GET)
    public Object findById(@RequestParam(value = "id",required = false) Long id){

        Iterable bList;
        if(id!=null){
            BankAccount user = accountDao.findById(id);
            if(user == null){
                return "该数据项不存在";
            }else{
                return "cardNo:" + user.getCardno() + " , name:" + user.getName()+",money:"+user.getMoney();
            }
        }else{
            bList = accountDao.findAll();

        }
        return bList;
    }
    @ApiOperation(value = "姓名查询银行用户信息")
    @RequestMapping(value = "findName",method = RequestMethod.GET)
    public List findName(@RequestParam(value = "name")String name){

        List bList = accountDao.findByNameLike(name);
        return bList;
    }
    @ApiOperation(value = "查询银行用户数据")
    @RequestMapping(value = "findIds",method = RequestMethod.GET)
    public List findIds(@RequestParam(value = "id")Integer id){

        List bList = accountDao.findOrderById(id);
        return bList;
    }

    @ApiOperation(value = "新增银行数据")
    @RequestMapping(value = "saveBankAccount",method = RequestMethod.POST)
    public String addBankAccount(@RequestParam(value ="cardNo") String cardNo, @RequestParam(value = "name") String name,
                                 @RequestParam(value = "money")BigDecimal money){
        BankAccount account = new BankAccount();
        account.setMoney(money);
        account.setName(name);
        account.setCardno(cardNo);
        accountDao.insertBank_account(cardNo,name,money);
        //accountDao.save(account);
        return " Add success!";//
    }

    @ApiOperation(value = "修改银行数据")
    @RequestMapping(value = "updateBankAccount",method = RequestMethod.POST)
    public String updateBankAccount(@RequestParam(value ="id") Long id, @RequestParam(value = "name") String name){
        accountDao.updateOne(id,name);
        return " update success!";
    }

    @ApiOperation(value = "删除银行数据")
    @RequestMapping(value = "delAccountId",method = RequestMethod.POST)
    public String delBankAccount(@RequestParam(value = "id") Long id){

       BankAccount user = accountDao.findById(id);
       if(user==null){
            return "该数据项不存在!";
       }else{
          // accountDao.delete(id);//jar自带的删除方法
           accountDao.deteteBankAccountById(id);//源生的删除方法
       }
        return "success!";
   }

     

具体的源码可以在这里进行下载如有需要的

http://download.csdn.net/download/juanmiao/10113527


你可能感兴趣的:(java,Jpa)