springboot–jpa03

pom.xml

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/nc
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

实体类Girl.java

package com.rick;

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

/**
 * Created by rick on 2017/1/10.
 */
@Entity
public class Girl {
    @Id
    @GeneratedValue
    private Integer id;

    private String cupSize;

    private Integer age;

    public Girl() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

daoGirlRepository.java自动被spring管理

package com.rick;

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

/**
 * Created by rick on 2017/1/10.
 */
public interface GirlRepository extends JpaRepository<Girl, Integer> {
}

service GirlService.java

package com.rick;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * Created by rick on 2017/1/10.
 */
@Service
public class GirlService {
    @Resource
    GirlRepository girlRepository;

    @Transactional //方法纳入事务
    public void addTwoGirls() {
        Girl girl1 = new Girl();
        girl1.setAge(11);
        girl1.setCupSize("A");
        girlRepository.save(girl1);

        Girl girl2 = new Girl();
        girl2.setAge(30);
        girl2.setCupSize("G");
        girlRepository.save(girl2);

    }
}

JpaRepository中的其他方法:

* java.util.List<T> findAll();
* java.util.List<T> findAll(org.springframework.data.domain.Sort sort);
* java.util.List<T> findAll(java.lang.Iterable<ID> iterable);
* <S extends T> java.util.List<S> save(java.lang.Iterable<S> iterable);
* void flush();
* <S extends T> S saveAndFlush(S s);
* void deleteInBatch(java.lang.Iterable<T> iterable);
* void deleteAllInBatch();
* T getOne(ID id);
* <S extends T> java.util.List<S> findAll(org.springframework.data.domain.Example<S> example);
* <S extends T> java.util.List<S> findAll(org.springframework.data.domain.Example<S> example, org.springframework.data.domain.Sort sort);