Mapped foreign key in Hibernate Entity - java

Hi write Spring application, using Spring Security. It's my database for user and account role:
create table users (
id int not null primary key,
username varchar2(20) not null unique,
password varchar2(20) not null,
firstName varchar2(20),
lastName varchar2(20),
personalId varchar2(11) unique,
city varchar2(40),
address varchar2(40),
email varchar2(30) unique,
phone varchar2(9) unique,
enabled number(1) not null
);
create table user_roles (
id int primary key,
name varchar2(20) not null,
username varchar(20) constraint username_fk references users(username) not null
);
My Entity classes:
#Entity
#Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#NotNull
#Column(name = "username")
private String username;
#NotNull
#Column(name = "password")
private String password;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "personalId")
private String personalId;
#Column(name = "city")
private String city;
#Column(name = "address")
private String address;
#Column(name = "email")
private String email;
#Column(name = "phone")
private String phone;
#NotNull
#Column(name = "enabled")
private int enabled;
#OneToMany(mappedBy = "username")
private Set<UserRole> userRoleSet = new HashSet<UserRole>(0);
#Entity
#Table(name = "user_roles")
public class UserRole implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#NotNull
#Column(name = "name")
private String name;
#JoinColumn(name = "username")
#ManyToOne(targetEntity = User.class)
private String username;
When I try login in my system i have error:
Hibernate: select userrolese0_.username as username3_1_0_, userrolese0_.id as id1_0_0_, userrolese0_.id as id1_0_1_, userrolese0_.name as name2_0_1_, userrolese0_.username as username3_0_1_ from user_roles userrolese0_ where userrolese0_.username=?
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1722, SQLState: 42000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ORA-01722: invalid number
My class implements UserDetailsService:
package pl.piotr.ibank.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.piotr.ibank.daointerface.UserDao;
import pl.piotr.ibank.model.UserRole;
#Transactional(readOnly = true)
#Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
#Autowired
UserDao userDao;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
pl.piotr.ibank.model.User user = userDao.findByUsername(username);
List<GrantedAuthority> authorities = buildUserAuthority(user
.getUserRole());
return buildUserForAuthentication(user, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getName()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(
setAuths);
return result;
}
private UserDetails buildUserForAuthentication(
pl.piotr.ibank.model.User user, List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), true, true,
true, true, authorities);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
I think so, my mapped foregin key for tables is bad. Example query from Userreturn users from table, but when i try get user_roles i have above error. Please check correctness my mapped. I using Oracle database and Hiberante.

The problem is, that when you're mapping entities Hibernate expects the foreign key to be the id of the referenced entity, i.e. you should map on user-id instead of username.
Also your entity mapping seems to be wrong: you use a ManyToOne with the target entity being User but the type of the property is String. AFAIK Hibernate would try to assign the user to username, which should fail miserably.
So the table should look like this:
create table user_roles (
id int primary key,
name varchar2(20) not null,
userid int constraint userid_fk references users(id) not null
);
And the mapping in UserRole should then be:
#JoinColumn(name = "userid")
#ManyToOne
private User user;
Plus the reverse mapping in User:
#OneToMany(mappedBy = "user")
private Set<UserRole> userRoleSet;
As a side note, please keep in mind that id is a special keyword in HQL, i.e. it will always reference an entity's id. If id always is the only property annotated with #Id then it's no problem, but if you change that you can run into problems with queries selecting the wrong data or even failing.

Related

Repeated column in mapping for entity in #OneToOne

I have two tables:
CREATE TABLE users
(
id INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(68) NOT NULL,
oldPassword VARCHAR(68),
enabled BOOLEAN NOT NULL
);
and
CREATE TABLE authorities (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
);
CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority);
Unfortunatelly instead of joining with authority_id which should be in users table I just have username which is the same in both tables.
In models I tried (ommited getters and setters):
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String oldPassword;
private boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "username", referencedColumnName = "username")
private Authorities authority;
}
and
#Entity
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String authority;
#OneToOne(mappedBy = "authority")
private User user;
}
but then I have an error: Repeated column in mapping for entity column: username (should be mapped with insert="false" update="false")
The reason you are getting usernames in both tables is that you have declared username column in both the tables.
Also, you have to map the relation based on the authority_id so the code of the models would look like this:
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String oldPassword;
private boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "authority_id", referencedColumnName = "id")
private Authorities authority;
}
#Entity
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String authority;
#OneToOne(mappedBy = "authority")
private User user;
}
And the tables will be created like this:
Hope this solves your problem.
The message is clear: you have a repeated column in the mapping, and a column "username" in both tables has repeated. Instead of this, you should use this :
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "authority_username", referencedColumnName = "username")
private Authorities authority;

Why is my Entity class inserting two Id's into my table? Spring Boot JPA

I have two Entity classes User and UserProfile. The User table has a primary key for the User ID which is a long data type. This User ID is supposed to be the primary key in user_profile as well. User also has email as a column, which I want to be linked to the user_profile also. The issue I am having is that for some reason, a column named id is being inserted into my table when I already have the primary key user_id set in the user_profile table. Does anyone know what I am doing wrong?
User:
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#Entity
#Table( name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
})
#SecondaryTable(name = "user_profile")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "username")
#NotBlank
#Size(max = 20)
private String username;
#Column(name = "email", table = "user_profile")
#NotBlank
#Size(max = 50)
#Email
private String email;
#NotBlank
#Size(max = 120)
private String password;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable( name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
//getter methods
//setter methods
}
User_Profile:
import javax.persistence.*;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
#Entity
#Table(name = "user_profile")
public class UserProfile {
#Id
private Long id;
#OneToOne(fetch = FetchType.LAZY)
#MapsId
private User user;
// #JoinColumn(name = "email")
// #OneToOne(fetch = FetchType.LAZY)
// private User email;
#Column(name = "profile_img") //S3 image Link
private String profile_img;
#Column(name = "profile_banner") //S3 image Link
private String profile_banner;
//getter methods
//setter methods
}
User table:
User_Profile table:
You can avoid the usage of SecondaryTable and use just OneToOne and mappedBy and #PrimaryKeyJoinColumn :
#Entity
#Table(#Table( name = "users",
uniqueConstraints = { #UniqueConstraint(columnNames = "username") }))
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
Long userId;
#OneToOne(mappedBy = "user")
UserProfile userProfile;
// Other fields
// getters and setters
}
#Entity
#Table(name = "user_profile")
public class UserProfile {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
Long userId;
#OneToOne
#PrimaryKeyJoinColumn(name = "user_id")
User user;
// other fields
// getters and setters
}
more details here https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables
I was not aware of #MapsId, learned something new.
A simple search and found following
can someone please explain me #MapsId in hibernate?
I tried with dummy code. It looks like we are mixing #SecondaryTable and #MapsId together.
The duplicate column is from SecondaryTable annotation.
i don't have full context of requirement here, mostly https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables should solve the need. #Oussama ZAGHDOUD also mentioned this in his response.
In summary, use #MapsId when you want to keep two separate entity class for 2 tables and #SecondaryTable combines 2 tables into one entity class. Both acts same way, primary key of one table works as primary key and foreign key of 2nd table.
With #MapsId only I was getting following sql
Hibernate: create table user_profile (profile_banner varchar(255), profile_img varchar(255), user_user_id bigint not null, primary key (user_user_id))
Hibernate: create table users (user_id bigint generated by default as identity, email varchar(50), password varchar(120), username varchar(20), primary key (user_id))
Hibernate: alter table users add constraint UKr43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table user_profile add constraint FKqkgvrni6161p23yj2lbp9xxlk foreign key (user_user_id) references users
With #SecondaryTable
Hibernate: create table user_profile (email varchar(50), profile_banner varchar(255), profile_img varchar(255), user_id bigint not null, primary key (user_id))
Hibernate: create table users (user_id bigint generated by default as identity, password varchar(120), username varchar(20), primary key (user_id))
Hibernate: alter table users add constraint UKr43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table user_profile add constraint FKuganfwvnbll4kn2a3jeyxtyi foreign key (user_id) references users
Entity class will look like below
package com.example.demo.entity;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#Entity
#Table( name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username")
})
#SecondaryTable(name = "user_profile", pkJoinColumns = #PrimaryKeyJoinColumn(name = "user_id"))
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="user_id")
private Long userId;
#Column(name = "username")
#NotBlank
#Size(max = 20)
private String username;
#Column(name = "email", table = "user_profile")
#NotBlank
#Size(max = 50)
#Email
private String email;
#Column(name = "profile_img", table = "user_profile") //S3 image Link
private String profile_img;
#Column(name = "profile_banner", table = "user_profile") //S3 image Link
private String profile_banner;
#NotBlank
#Size(max = 120)
private String password;
//getter methods
//setter methods
}

OneToOne with hibernate JPA

I'm trying to relate two tables
User and Address
A user has a single address, an address belongs to only one user. Keys are listed by the ID of an Address
so I create my address first and then I create a user and link it with an address id
But I can't do it at all, I have the following error in return:
Error creating bean with name 'entityManagerFactory' defined in class path resource [org / springframework / boot / autoconfigure / orm / jpa / HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException: Cannot invoke "org.hibernate.mapping.PersistentClass.getTable ()" because "classMapping" is null
i'm totally new to hibernate but i need this project for college so forgive me for the ignorance on the subject
Thats my code:
USER/USUARIO Class:
import org.hibernate.validator.constraints.br.CPF;
import javax.persistence.*;
import javax.validation.constraints.*;
public class Usuario{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
#NotNull
#Size(min = 5,max = 30)
#Pattern(regexp = "^[a-zA-Z\s]*$", message = "Nome inválido! Digite apenas letras e espaçamento") //Permite apenas letras e espaço
private String nome;
#NotNull
#CPF
private String cpf;
#NotNull
#Email
private String email;
#NotNull
#Size(min = 5,max = 12)
private String senha;
private Integer telefone;
#DecimalMin("0")
#DecimalMax("5")
private Double avaliacao;
#NotNull
#OneToOne(cascade = CascadeType.ALL,mappedBy = "id")
private Endereco endereco;
//Atributos para usuários autônomos
private Boolean isAutonomo;
private String categoriaAutonomo;
private Double precoAutonomo;
//Getters and Setters
ADRESS/ENDERECO Class
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "endereco")
public class Endereco {
#Id
#OneToOne
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#NotNull
#Size(min = 8,max = 8)
private String cep;
#NotNull
private String bairro;
#NotNull
private String logradouro;
#NotNull
private Integer numeroLogradouro;
private String complemento;
#NotNull
#Size(min = 2,max = 2)
private String uf;
#NotNull
private String cidade;
CONTROLLER
import br.com.bandtec.projetocaputeam.dominio.*;
import br.com.bandtec.projetocaputeam.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
#RestController
#RequestMapping("/caputeam")
public class CaputeamController {
#Autowired
private UsuariosRepository usuariosRepository;
#Autowired
private EnderecoRepository enderecoRepository;
//--- USERS
#GetMapping("/usuarios")
public ResponseEntity getUsuarios(){
List<Usuario> usuarios = usuariosRepository.findAll();
return !usuarios.isEmpty() ? ResponseEntity.status(200).body(usuarios) :
ResponseEntity.status(204).build();
}
#PostMapping("/cadastrar-usuario")
public ResponseEntity cadastrarUsuario(#RequestBody #Valid Usuario novoUsuario){
usuariosRepository.save(novoUsuario);
return ResponseEntity.ok().build();
}
//--- ADRESS
#PostMapping("/cadastrar-endereco")
public ResponseEntity cadastrarEndereco(#RequestBody #Valid Endereco novoEndereco){
enderecoRepository.save(novoEndereco);
return ResponseEntity.ok().build();
}
}
APPLICATION
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ProjetoCaputeamApplication {
public static void main(String[] args) {
SpringApplication.run(ProjetoCaputeamApplication.class, args);
}
}
And thats my Logic Model
EDIT
I tried to delete the "mapped by" part and remove the #OneToOne from Address but now it returns the following error when I try to send an POST of Adress:
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: "FKMXNOON0IKGA83W1A203Y6OFPN: PUBLIC.ENDERECO FOREIGN KEY(ID) REFERENCES PUBLIC.USUARIO(ID) (1)"; SQL statement:
insert into endereco (bairro, cep, cidade, complemento, logradouro, numero_logradouro, uf, id) values (?, ?, ?, ?, ?, ?, ?, ?) [23506-200]
as if he didn’t enter any Address fields
Im sending my POST by Postman like this:
{
"bairro": "Vila Prmavera",
"cep": "03388110",
"cidade": "São Paulo",
"complemento": "b1",
"logradouro": "Rua das dores",
"numeroLogradouro": 7,
"uf": "SP"
}
Don't map on the Id. Map means entity mapping not id mapping.
public class Endereco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne
private Usuario usuario
....
}
Or if you don't want Endereco to hold a reference to a Usuario just remove it. But you can't place #OneToOne on the id field. If you have only on one side the #OneToOne then you need also the annotation #MapsId.
public class Usario {
#NotNull
#MapsId
#OneToOne(cascade = CascadeType.ALL)
private Endereco endereco;
public class Endereco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id
}
Because #OneToOne tries to Map with an entity which means to a table in Database. For id there isn't any entity or Table in the database. That is why it complains

Why Doesn't jpa add data to the foreign key value

I have a users table which contains the user details. i also have a authorities table which has the role of a user. The user and authorities table has one to many mapping. When i try to save the details using Jpa the foreign key column is blank no data is inserted in that field. i have a form in which i am specifying the role of the user along with other details.
package com.example.StarsProject.Model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Table
#Getter
#Setter
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String role;
#ManyToOne(cascade = CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinColumn(name = "users_id", referencedColumnName = "id")
private Users users;
public Authorities(String role){
this.role = role;
}
}
package com.example.StarsProject.Model;
import com.example.StarsProject.DTO.UserDTO;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table
#Getter
#Setter
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "first_name")
private String firstname;
#Column(name = "last_name")
private String lastname;
#Column(unique = true)
private String email;
private String password;
#OneToMany(fetch = FetchType.EAGER,targetEntity = Authorities.class,mappedBy = "users", cascade = CascadeType.PERSIST)
private Set<Authorities> authorities;
public Users(UserDTO userDTO) {
this.email = userDTO.getEmail();
this.firstname = userDTO.getFirstname();
this.lastname = userDTO.getLastname();
this.password = userDTO.getPassword();
// Authorities authorities = new Authorities();
// authorities.setRole(userDTO.getRole());
// Set<Authorities> set = new HashSet<>();
// set.add(authorities);
this.authorities = new HashSet<Authorities>(Arrays.asList(new Authorities(userDTO.getRole())));
}
}
package com.example.StarsProject.Service;
import com.example.StarsProject.DTO.UserDTO;
import com.example.StarsProject.Model.Users;
import com.example.StarsProject.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserDetailsServiceImpl implements UserDetailsServiceInterface{
#Autowired
UserRepository userRepository;
#Override
public void storeUserDetails(UserDTO userDTO) {
Users users = new Users(userDTO);
userRepository.save(users);
}
}
When i try to save the user details it doesn't insert any value in the foreign key column. Can someone tell me what i am doing wrong.
You need to setusers field in Authorities manually. Hibernate won't fill it for you.

Associating two tables with hibernate annotations

I am new to Hibernate, so please forgive me if the question is duplicated or stupid. I am using Hibernate 3.3.0, PostgreSQL DB. Right now I have 2 entities. I need to associate them with #OneToMany annotation in such way, that User.roleID was PK and Role.id was FK (user can have only one role, and the same role can be assigned to many users). Also as I was searching Google, I found out that for some reason every example with annotation associations has the annotated field declared as Set. Please, explain this to me. Thank you in advice.
Nazar.
User entity:
package com.dataart.mediaportal.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User implements Serializable {
private int id;
private String login;
private String password;
private String firstName;
private String lastName;
private int roleID;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id", unique = true)
public int getId() {
return id;
}
#Column(name = "user_login", nullable=false, unique = true, length = 20 )
public String getLogin() {
return login;
}
#Column(name = "user_password", nullable = false, length = 32)
public String getPassword() {
return password;
}
#Column(name = "user_name", nullable = true)
public String getFirstName() {
return firstName;
}
#Column(name = "user_lastname", nullable = true)
public String getLastName() {
return lastName;
}
#Column(name = "role_id", nullable = false)
public int getRoleID() {
return roleID;
}
public void setRoleID(int roleID) {
this.roleID = roleID;
}
public void setId(int id) {
this.id = id;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setFirstName(String firstname) {
this.firstName = firstname;
}
public void setLastName(String lastname) {
this.lastName = lastname;
}
}
Role entity:
package com.dataart.mediaportal.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "roles")
public class Role implements Serializable {
private int id;
private String role;
#Id
#Column(name = "role_id", nullable = false)
public int getId() {
return id;
}
#Column(name = "role_name", nullable = false)
public String getRole() {
return role;
}
public void setId(int id) {
this.id = id;
}
public void setRole(String role) {
this.role = role;
}
}
DB Script:
DROP TABLE IF EXISTS users CASCADE;
DROP TABLE IF EXISTS roles CASCADE;
DROP TABLE IF EXISTS albums CASCADE;
DROP TABLE IF EXISTS images CASCADE;
CREATE TABLE users
(
user_login character varying(20) NOT NULL,
user_password character varying(32) NOT NULL,
user_name character varying,
user_lastname character varying,
role_id integer DEFAULT 0,
user_id serial NOT NULL,
CONSTRAINT pk_user_id PRIMARY KEY (user_id),
CONSTRAINT users_user_login_key UNIQUE (user_login)
)
WITH (
OIDS=FALSE
);
ALTER TABLE users
OWNER TO postgres;
CREATE TABLE roles
(
role_id integer NOT NULL,
role_name character varying NOT NULL DEFAULT 'user'::character varying,
CONSTRAINT role_id_pk PRIMARY KEY (role_id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE roles
OWNER TO postgres;
INSERT INTO roles
VALUES ( 0, 'user' ),
( 1, 'admin' );
-- testlog - testpass
-- user - password
INSERT INTO users
VALUES ( 'testlog', '179ad45c6ce2cb97cf1029e212046e81', 'Nazar', 'Sobchuk', 1),
('user', '5f4dcc3b5aa765d61d8327deb882cf99', 'unknown', 'unknown', 0);
CREATE TABLE albums
(
album_name character varying NOT NULL,
user_id integer,
album_id serial NOT NULL,
CONSTRAINT album_id PRIMARY KEY (album_id),
CONSTRAINT user_id FOREIGN KEY (user_id)
REFERENCES users (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE albums
OWNER TO postgres;
CREATE INDEX fki_user_id
ON albums
USING btree
(user_id);
INSERT INTO albums VALUES ('Main Album', 1);
CREATE TABLE images
(
img bytea,
img_name character varying NOT NULL,
album_id integer,
img_id serial NOT NULL,
CONSTRAINT images_img_name UNIQUE(img_name),
CONSTRAINT album_id FOREIGN KEY (album_id)
REFERENCES albums (album_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE images
OWNER TO postgres;
CREATE INDEX fki_album_id
ON images
USING btree
(album_id);
Insert user:
public boolean insertUser(User user) {
factory = getSessionFactory();
session = factory.openSession();
tx = session.beginTransaction();
Query queryResult = session.createQuery("from User");
List<User> userList = queryResult.list();
for (User u : userList) {
if (u.getLogin().equalsIgnoreCase(user.getLogin())) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("User_is_already_registered"));
return false;
}
}
session.save(user);
tx.commit();
session.close();
return true;
}
Add the user as one to many relationship to Role as below. create the setters as well
private List<User> userList;
#OneToMany(mappedBy = "role")
public List<User> getUserList() {
return userList;
}
Add the Role as many to one relationship to User as below
private Role role;
#ManyToOne
public Role getRole() {
return role;
}

Categories