Hibernate Неизвестный список полей столбца "clazz_" - PullRequest
1 голос
/ 28 мая 2020

Как новичок, я делаю небольшой проект в образовательных целях: Форма входа / регистрации с использованием Spring MVC / Hibernate.

Перед тем, как копаться в проблеме, я покажет вам мою Entity – Relationship & Relational модель. Для регистрации я создам объект Account и setRole ("USER") .

Модель ER:

enter image description here

And its translation to RM model:

введите описание изображения здесь

СЕЙЧАС ПОКРЫВАЕМ КОД!

В нашем контексте мы сосредоточимся на этих сущностях

Account.java
MemberAccount.java  (extending Account.java)
Role.java
LogEntry.java

БИЗНЕС-ЛОГИН C:

@Service
public class AccountRegistrationServiceImpl implements RegistrationService<Object> {

@Autowired
private AccountRepository mAccountRepository;

@Autowired
private RoleRepository mRoleRepository;


// Method used to insert record
public void register(Object obj) {
    Account account = (Account) obj;

    account.setRoles(new HashSet<Role>(mRoleRepository.findAllByDescription("USER")));
    account.setType("DirectLogin");

    mAccountRepository.save(account);
}


// Find an existing 'mailAccount' (-> an User is already registered with this mail account) 
public List<Object> checkIfAccountExists(Object obj) {
    String mailAccount = (String) obj;
    
    return mAccountRepository.findByMailAccount(mailAccount);
}
}



public interface RoleRepository extends CrudRepository<Role, Long> {
    // SELECT r1_0.id, r1_0.description FROM role as r1_0 WHERE r1_0.description = roleDescription
    public List<Role> findAllByDescription(String roleDescription);
}

public interface AccountRepositoryextends CrudRepository<Account, Long> {
    public List<Object> findByMailAccount(String emailAccount);
}

Аккаунт. java

 @Data                                        // Lombok library to avoid writing getter/setter
 @Entity
 @Table(name = "account")
 @Access(value = AccessType.FIELD)
 @Inheritance(strategy = InheritanceType.JOINED)
 public class Account {

@Id
@GeneratedValue
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "accountType")
private String type;

@Column(name = "availability")
private Boolean availability;

@Column(name = "email", nullable = false)
private String mailAccount;

@Column(name = "username", nullable = false)
private String userName;

@Column(name = "password")
private String password;

@Transient                                  // Will not be persisted
private String passwordConfirm;


@ManyToMany
@JoinTable(name = "hasRoles", joinColumns = @JoinColumn(name = "aId", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "rId", referencedColumnName = "id"))
private Set<Role> roles;


@OneToMany(mappedBy = "user")
private List<LogEntry> logs;
}

MemberAccount. java

@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "memberAccount")
@PrimaryKeyJoinColumn(name = "id")
public class MemberAccount extends Account {

/*
 * 'id' and 'type' are defined from Account.java.
 * 
 * In DB language: They have their own id' and 'type' columns.
 */


@Column(name = "firstname")
private String firstName;

@Column(name = "lastname")
private String lastName;

@Column(name = "birthDate")
private String birthDate;

@Column(name = "gender")
private String gender;

@Column(name = "civilstatus")
private String civilStatus;

@Column(name = "profession")
private String profession;

@Column(name = "street")
private String streetName;

@Column(name = "streetNbr")
private String streetNumber;

@Column(name = "city")
private String city;

@Column(name = "zip")
private String zipCode;

@Column(name = "country")
private String country;

}

Роль. java

@Data
@Entity
@Table(name = "role")
@Access(value = AccessType.FIELD)
public class Role {

@Id
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "description")
private String description;

@ManyToMany(mappedBy = "roles")
private Set<Account> accounts;
}

LogEntry. java

@Data
@Entity
@Table(name = "logEntry")
@Access(value = AccessType.FIELD)
public class LogEntry {

@Id
@GeneratedValue
@Column(name = "id", nullable = false)
private Long id;

@ManyToOne
@JoinColumn(name = "affiliatedUserId")
private Account user;

@Column(name = "loginDate")
private Date loginDate;

@Column(name = "logoutDate")
private Date logoutDate;

}

И ... наш SQL скрипт

DROP DATABASE springlogin_db;
CREATE DATABASE IF NOT EXISTS springlogin_db

DROP TABLE IF EXISTS account;
CREATE TABLE account (
    id BIGINT,
    accountType varchar(20),
    availability boolean,
    userName varchar(30),
    email varchar(30),
    password varchar(20)) 
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


DROP TABLE IF EXISTS role;
CREATE TABLE role (
    id BIGINT,
    description varchar(20))
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


DROP TABLE IF EXISTS hasRoles;
CREATE TABLE hasRoles (
    aId BIGINT,
    rId BIGINT)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


DROP TABLE IF EXISTS logEntry;
CREATE TABLE logEntry (
   id BIGINT,
   affiliatedUserId BIGINT,
   loginDate DATE,
   logoutDate DATE)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


DROP TABLE IF EXISTS memberAccount;
CREATE TABLE memberAccount (
    id BIGINT,
    accountType varchar(20),
    firstname varchar(20),
    lastname varchar(20),
    birthDate varchar(11),
    gender varchar(10),
    civilstatus varchar(10),
    profession varchar(20),
    street varchar(30),
    streetNbr int,
    city varchar(20),
    zip int,
    country varchar(20))
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


ALTER TABLE account
ADD PRIMARY KEY(id);

ALTER TABLE role
ADD PRIMARY KEY(id);

ALTER TABLE hasRoles
ADD CONSTRAINT FK_hasRoles_accountId_id FOREIGN KEY(aId) REFERENCES account(id) ON DELETE CASCADE ON CASCADE;
ALTER TABLE hasRoles
ADD CONSTRAINT FK_hasRoles_roleId_id FOREIGN KEY(rId) REFERENCES role(id) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE logEntry
ADD PRIMARY KEY(id);
ALTER TABLE logEntry
ADD CONSTRAINT FK_logEntry_affiliatedUserId_id FOREIGN KEY(affiliatedUserId) REFERENCES account(id);

ALTER TABLE memberAccount
ADD PRIMARY KEY(id);


INSERT INTO role
VALUES ('1', 'USER'),('2', 'ADMIN'); 

При поиске роли «ПОЛЬЗОВАТЕЛЬ» мое приложение выполнит

account.setRoles(new HashSet<Role>(mRoleRepository.findAllByDescription("USER")));

Вот некоторые SQL Hibernate работает позади:

select
    r1_0.id,
    r1_0.description 
from
    role as r1_0 
where
    r1_0.description = ?

Прежде чем продолжить к остальной части кода, мое приложение cra sh на данный момент:

select
    a1_0.rId,
    a1_1.id,
    a1_1.clazz_,
    a1_1.availability,
    a1_1.email,
    a1_1.password,
    a1_1.accountType,
    a1_1.username,
    a1_2.birthDate,
    a1_2.city,
    a1_2.civilstatus,
    a1_2.country,
    a1_2.firstname,
    a1_2.gender,
    a1_2.lastname,
    a1_2.profession,
    a1_2.street,
    a1_2.streetNbr,
    a1_2.zip 
from
    hasRoles as a1_0 
left outer join
    account as a1_1 
        on a1_0.aId = a1_1.id 
left outer join
    memberAccount as a1_2 
        on a1_1.id = a1_2.id 
where
    a1_0.rId = ?

Я подозреваю, что Hibernate создает этот столбец «clazz_» , но я не вижу, что такое Я пропустил свой код. Извините за этот ДЛИННЫЙ пост.

С уважением

...