JPA OneToMany не удается создать сущность. Ошибка ConstraintViolationException

121
07 января 2021, 06:30
@Test
    public void add() {
        Client client = clientRepo.findById(6L).get();
        BankCard bankCard = new BankCard();
        bankCard.setName("tinkov");
        bankCard.setNumber("321312321312");
        client.setCards(Sets.newSet(bankCard));
        client.setUsername("GERa");
        clientRepo.save(client);
    }

При выполнение кода получаю ошибку, но причина мне не ясна. Почему при создание банковской карты не находится user_id ведь я создаю через него, почему orm не исправляет этой проблемы ? Как исправить проблему ?

Hibernate: select client0_.id as id1_16_0_, client0_1_.activate as activate2_16_0_, client0_1_.activation_code as activati3_16_0_, client0_1_.create_date_time as create_d4_16_0_, client0_1_.email as email5_16_0_, client0_1_.enabled as enabled6_16_0_, client0_1_.fullname as fullname7_16_0_, client0_1_.password as password8_16_0_, client0_1_.role as role9_16_0_, client0_1_.username as usernam10_16_0_, client0_.city_id as city_id4_3_0_, client0_.reviews_negative as reviews_1_3_0_, client0_.reviews_positive as reviews_2_3_0_, cards1_.user_id as user_id4_0_1_, cards1_.id as id1_0_1_, cards1_.id as id1_0_2_, cards1_.name as name2_0_2_, cards1_.number as number3_0_2_, cards1_.user_id as user_id4_0_2_, city2_.id as id1_2_3_, city2_.name as name2_2_3_, city2_.region_id as region_i3_2_3_, region3_.id as id1_13_4_, region3_.name as name2_13_4_, deliveryad4_.client_user_id as client_u8_4_5_, deliveryad4_.id as id1_4_5_, deliveryad4_.id as id1_4_6_, deliveryad4_.appartment as appartme2_4_6_, deliveryad4_.city_id as city_id7_4_6_, deliveryad4_.fullname as fullname3_4_6_, deliveryad4_.house as house4_4_6_, deliveryad4_.index as index5_4_6_, deliveryad4_.client_user_id as client_u8_4_6_, deliveryad4_.street as street6_4_6_, city5_.id as id1_2_7_, city5_.name as name2_2_7_, city5_.region_id as region_i3_2_7_ from client client0_ inner join user client0_1_ on client0_.id=client0_1_.id left outer join bank_card cards1_ on client0_.id=cards1_.user_id left outer join city city2_ on client0_.city_id=city2_.id left outer join region region3_ on city2_.region_id=region3_.id left outer join delivery_adress deliveryad4_ on client0_.id=deliveryad4_.client_user_id left outer join city city5_ on deliveryad4_.city_id=city5_.id where client0_.id=?
Hibernate: select client0_.id as id1_16_0_, client0_1_.activate as activate2_16_0_, client0_1_.activation_code as activati3_16_0_, client0_1_.create_date_time as create_d4_16_0_, client0_1_.email as email5_16_0_, client0_1_.enabled as enabled6_16_0_, client0_1_.fullname as fullname7_16_0_, client0_1_.password as password8_16_0_, client0_1_.role as role9_16_0_, client0_1_.username as usernam10_16_0_, client0_.city_id as city_id4_3_0_, client0_.reviews_negative as reviews_1_3_0_, client0_.reviews_positive as reviews_2_3_0_ from client client0_ inner join user client0_1_ on client0_.id=client0_1_.id where client0_.id=?
Hibernate: select deliveryad0_.client_user_id as client_u8_4_0_, deliveryad0_.id as id1_4_0_, deliveryad0_.id as id1_4_1_, deliveryad0_.appartment as appartme2_4_1_, deliveryad0_.city_id as city_id7_4_1_, deliveryad0_.fullname as fullname3_4_1_, deliveryad0_.house as house4_4_1_, deliveryad0_.index as index5_4_1_, deliveryad0_.client_user_id as client_u8_4_1_, deliveryad0_.street as street6_4_1_, city1_.id as id1_2_2_, city1_.name as name2_2_2_, city1_.region_id as region_i3_2_2_, region2_.id as id1_13_3_, region2_.name as name2_13_3_ from delivery_adress deliveryad0_ left outer join city city1_ on deliveryad0_.city_id=city1_.id left outer join region region2_ on city1_.region_id=region2_.id where deliveryad0_.client_user_id=?
Hibernate: select cards0_.user_id as user_id4_0_0_, cards0_.id as id1_0_0_, cards0_.id as id1_0_1_, cards0_.name as name2_0_1_, cards0_.number as number3_0_1_, cards0_.user_id as user_id4_0_1_ from bank_card cards0_ where cards0_.user_id=?
Hibernate: insert into bank_card (name, number, user_id) values (?, ?, ?)
2019-05-26 02:34:11.788  WARN 18228 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
2019-05-26 02:34:11.788 ERROR 18228 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'name' cannot be null
2019-05-26 02:34:11.789 ERROR 18228 --- [           main] o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

ClientRepo

@Repository
public interface ClientRepo extends JpaRepository<Client,Long> {
    Optional<Client> findById(Long id);
}

Класс Client

package com.fianma.auction.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
import java.util.Set;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Client extends User
{
    private int reviewsPositive;
    private int reviewsNegative;
    @OneToMany(mappedBy = "owner",fetch = FetchType.EAGER)
    private Set<DeliveryAdress> deliveryAdresses;
    @OneToMany(mappedBy = "owner",fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
    private Set<BankCard> cards;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="city_id")
    private City city;
    @OneToMany(mappedBy = "seller",fetch = FetchType.LAZY)
    private List<Lot> lots;
    @OneToMany(mappedBy = "buyer",fetch = FetchType.LAZY)
    private List<Order> purchasedOrders;
    @OneToMany(mappedBy = "seller",fetch = FetchType.LAZY)
    private List<Order> sellingOrders;
}

Класс BankCard

package com.fianma.auction.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "bank_card")
public class BankCard {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String number;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="user_id")
    private Client owner;
}

Класс User

*@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class  User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotBlank(message = "Имя пользователя не может быть пустым")
    private String fullname;
    @NotBlank(message = "Логин не может быть пустым")
    private String username;
    @NotBlank(message = "Пароль не может быть пустым")
    private String password;
    private boolean enabled;
    private boolean activate;
    @Email(message = "Не корректный email")
    @NotBlank(message = "Email не может быть пустым")
    private String email;
    @Enumerated(EnumType.STRING)
    private Role role;
    @JsonIgnore
    private String activationCode;
    private LocalDateTime createDateTime;
    @OneToMany(mappedBy = "author",fetch = FetchType.LAZY)
    private List<OrderNegotiation> orderNegotiation;
    @Override @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singleton(role);
    }
    @Override @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override @JsonIgnore
    public boolean isAccountNonLocked() {
        return activate;
    }
    @Override @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override @JsonIgnore
    public boolean isEnabled() {
        return enabled;
    }
}*
READ ALSO
Управление объектом в игре на java в android

Управление объектом в игре на java в android

Я делаю небольшую игру - ретро-гонкуИ для управления автомобилем я решил использовать нажатия на экран

144
Вывод сложения целых чисел в конслои. Java

Вывод сложения целых чисел в конслои. Java

Я новичокПрошу прощения заранее, если вопрос глупый

109
Конфигурация спринг

Конфигурация спринг

есть вот такой контекст xml

114