我花了几天时间解决一个奇怪的问题。StackOverflow 中有很多类似的帖子,我已经检查了很多,但我找不到与此类似的内容。我有一个Human
家长班
import javax.persistence.*;
import java.util.Date;
@Entity(name = "Human")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Human
{
@Id
@Column(name = "human_id", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@JsonProperty("name")
private String name;
@JsonProperty("date_of_birth")
private Date dateOfBirth;
@Embedded
@JsonProperty("authentication_credential")
private AuthenticationCredentials authCred;
// constructors + setter/getters
}
一个User
子类:
import javax.persistence.*;
import java.util.Date;
@Entity(name = "User")
@Table(name = "end_user")
public class User extends Human
{
@OneToOne(mappedBy = "user",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
optional = false)
@JsonProperty("contact_numbers")
private CollectionOfContactMethods contactNumbers;
@JsonProperty("telephone")
private String telephone;
// constructors + setter/getters
}
并且还CollectionOfContactMethods
与 的构成关系User
。
import javax.persistence.*;
import java.util.List;
@Entity(name = "CollectionOfContactMethods")
@Table(name = "collection_of_contact_methods")
public class CollectionOfContactMethods
{
@Id
@Column(name = "collection_id", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ext_human_id", referencedColumnName = "human_id")
private User user;
@JsonProperty("email")
private String email;
// constructors + setter/getters
}
根据 ER 图,计划是这样的:
但是,我在数据库级别得到的是:
我很感激你花费的时间。谢谢。
PS:这里是UserController
@RestController
@RequestMapping("api/v1/user/")
public class UserController
{
@Autowired
UserService userService;
@GetMapping(value = "users")
Iterable<User> list()
{
Iterable<User> retVal = userService.findAll();
return retVal;
}
@RequestMapping(value = "user", method = RequestMethod.POST)
User create(@RequestBody User user)
{
return userService.save(user);
}
@RequestMapping(value = "user/{id}", method = RequestMethod.GET )
Optional<User> get(@PathVariable Long id)
{
return userService.findById(id);
}
}
还有UserService
:
import com.tsakirogf.schedu.model.human.User;
import org.springframework.data.repository.CrudRepository;
public interface UserService extends CrudRepository<User, Long>
{
}