是否可以为共享类定义Spring存储库?

时间:2017-07-23 12:05:44

标签: spring spring-boot spring-data-jpa

我有一个类User,它在服务器和android客户端之间共享。所以我不想用@id注释来注释班级。

在spring-jpa中处理这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是回退到xml映射,以便您的域对象保持纯粹。

Spring-boot会注意到你正在使用这种类型的映射并为你开箱即用。

这是一个简单的例子:

package com.stackoverflow.so45264894;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;

@SpringBootApplication
@EnableJpaRepositories
public class So45264894Application {

    public static void main(String[] args) {
        SpringApplication.run(So45264894Application.class, args);
    }

    public static class User {
        private Long   id;
        private String username;

        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
    }

    @Bean
    CommandLineRunner run(UserRepository userRepository) {
        final User user = new User();
        user.setUsername("admin");
        return args -> userRepository.save(user);
    }
}

interface UserRepository extends CrudRepository<So45264894Application.User, Long> {
}

/src/main/resources/com/stackoverflow/so45264894/User.hbm.xml

映射
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.stackoverflow.so45264894" default-access="field">
    <class name="com.stackoverflow.so45264894.So45264894Application$User" table="users" dynamic-update="true">
        <id name="id" type="java.lang.Long">
            <column name="user_id" sql-type="integer"/>
            <generator class="identity"/>
        </id>
        <property name="username" column="username" unique="true"/>
    </class>
</hibernate-mapping>

输出:

Hibernate: drop table users if exists
Hibernate: create table users (user_id integer generated by default as identity, username varchar(255), primary key (user_id))
Hibernate: alter table users add constraint UK_r43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: insert into users (username, user_id) values (?, ?) // <- this is userRepository.save() call