SpringDataJPA is a sub-project of SpringData that significantly reduces the amount of code required for JPA as a Data access solution by providing a JPA-based Repository. You just need to write an interface that integrates with SpringDataJPA internally defined interfaces to perform simple CRUD operations.

preface

This article guides you through Spring Boot, Spring Data JPA, and MySQL implementations to set @id@GeneratedValue to an initial value increment from 10000.

To prepare

  • JDK 1.8 or later
  • Maven 3 or later
  • MySQL Server 5.6

Technology stack

  • Spring Data JPA
  • Spring Boot
  • MySQL

The directory structure

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/3/9/16209a19fc284657~tplv-t2oaga2asx-image.image

Father pom. XML

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.merryyou</groupId>
    <artifactId>jpa-example</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <modules>
        <module>one-to-one-foreignkey</module>
        <module>one-to-one-primarykey</module>
        <module>one-to-many</module>
        <module>many-to-many</module>
        <module>many-to-many-extra-columns</module>
        <module>initial-value-generator</module>
    </modules>
    <packaging>pom</packaging>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>Brussels-SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
Copy the code

@id@generatedValue Sets the initial value

The directory structure

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/3/9/16209a19fc4456dd~tplv-t2oaga2asx-image.image

pom.xml
<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>jpa-example</artifactId>
        <groupId>cn.merryyou</groupId>
        <version>1.0 the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>initial-value-generator</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1 track</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code
db.sql
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for address
-- ----------------------------
DROP TABLE IF EXISTS `address`;
CREATE TABLE `address` (
  `id` bigint(20) NOT NULL.`city` varchar(255) DEFAULT NULL.`state` varchar(255) DEFAULT NULL.`street` varchar(255) DEFAULT NULL.`zip` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`))ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of address
-- ----------------------------

-- ----------------------------
-- Table structure for app_seq_store
-- ----------------------------
DROP TABLE IF EXISTS `app_seq_store`;
CREATE TABLE `app_seq_store` (
  `APP_SEQ_NAME` varchar(255) NOT NULL.`APP_SEQ_VALUE` int(11) NOT NULL,
  PRIMARY KEY (`APP_SEQ_NAME`))ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of app_seq_store
-- ----------------------------
INSERT INTO `app_seq_store` VALUES ('LISTENER_PK'.'10000');

Copy the code
Entity class
Address
@Entity
public class Address {
    @Id
    @Column( name = "ID" )
    @TableGenerator(
            name = "AppSeqStore",
            table = "APP_SEQ_STORE",
            pkColumnName = "APP_SEQ_NAME",
            pkColumnValue = "LISTENER_PK",
            valueColumnName = "APP_SEQ_VALUE",
            initialValue = 10000,
            allocationSize = 1 )
    @GeneratedValue( strategy = GenerationType.TABLE, generator = "AppSeqStore" )
    private long id;

    private String street;

    private String city;

    private String state;

    private String zip;

    public long getId(a) {
        return id;
    }

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

    public String getStreet(a) {
        return street;
    }

    public void setStreet(String address) {
        this.street = address;
    }

    public String getCity(a) {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState(a) {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip(a) {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String toString(a) {
        return "Address id: " + getId() + ", street: " + getStreet() + ", city: " + getCity()
                + ", state: " + getState() + ", zip: " + getZip();
    }
Copy the code
  • @table declares the Table of data that this object maps to the database by specifying the names of tables (TALbe), directories (Catalog), and schemas for entities. This annotation is not required; if not, the system uses the default (the short class name of the entity).

  • @id declares this property as the primary key. This attribute value can be created by itself, but Hibernate recommends that it be generated by Hibernate

  • @GeneratedValue specifies the primary key generation strategy.

    1. TABLE: Uses a TABLE to store id values
    2. IDENTITY: identitycolumn
    3. SEQUENCR :sequence
    4. AUTO: Use the preceding three parameters based on the database
  • @column declares the mapping of this property to a database field.

  • Name Specifies the name of the primary key generation policy for this table, which is referenced in the “generator” value set in @GeneratedValue.

  • Table specifies the name of the table to be persisted by the table generation policy.

  • PkColumnName Specifies the name of the key value corresponding to the primary key generation policy in the persistent table.

  • ValueColumnName specifies the value currently generated by the primary key in the persistent table. Its value will be accumulated with each creation.

  • PkColumnValue declares the primary key corresponding to the build policy in the persistent table.

  • InitialValue specifies the initialValue of the primary key. The default value is 0

  • AllocationSize Specifies the size of each primary key increment

Spring Data JPA Repository
AddressRepository
public interface AddressRepository extends JpaRepository<Address.Integer> {}Copy the code

Spring Data JPA includes built-in repositories that implement common methods: Findone, FindAll, Save, etc.

application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost/initial-value-generator
    username: root
    password: admin
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    show-sql: true
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
# hibernate:
# ddl-auto: create
Copy the code
AddressRepositoryTest
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class AddressRepositoryTest {

    @Autowired
    private AddressRepository addressRepository;

    @Test
    public void testSave(a){
        Address address = new Address();
        address.setCity("beijing");
        address.setState(".");
        address.setStreet("street");
        address.setZip("aa.zip");
        Address result = addressRepository.save(address);
        Assert.assertNotNull(result);
        Assert.assertNotNull(result.getId());
        Assert.assertTrue(result.getId()>=10000); }}Copy the code

The code download

Download it from my Github, github.com/longfeizhen…


  1. JPA relational mapping series 1: One-to-one foreign key association
  2. JPA relational mapping series 2: One-to-one primary key association
  3. JPA relational mapping series three: One-to-many and many-to-one
  4. JPA relational mapping series 4: Many-to-many association mappings
  5. JPA Relational Mapping Series 5: Many-to-many relational tables have additional field relational mappings

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/3/9/16209a19fc30f23d~tplv-t2oaga2asx-image.image

🙂🙂🙂 focus on wechat small program Java architect journey Bored on the commute? Still reading novels, news? Don’t know how to improve your skills? Here’s the Java architecture article you need. 1.5W + Java engineers are reading it. What are you waiting for?