1

Есть следующие сущности:

@Entity
public class City {
    public City() {
    }

    public City(String name, Country country, String district, int population) {
        this.name = name;
        this.country = country;
        this.district = district;
        this.population = population;
    }

    @Id
    @SequenceGenerator(name = "city_id_sequence", sequenceName = "city_id_sequence", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "city_id_sequence")
    private int id;


    @OneToOne(optional =false, mappedBy = "capital")
    private Country country;

    private String name;

    private String district;

    private int population;

//geters and setters
}

и

@Entity
@Table(name = "country")
public class Country {
    public Country() {
    }

    public Country(String code, String name, String continent, String region, double area, int year,
                   int population, double lifeExp, double gnp, double gnpOld, String localName,
                   String governmentForm, String headOfState, City capital, String code2) {
        this.code = code;
        this.name = name;
        this.continent = continent;
        this.region = region;
        this.area = area;
        this.year = year;
        this.population = population;
        this.lifeExp = lifeExp;
        this.gnp = gnp;
        this.gnpOld = gnpOld;
        this.localName = localName;
        this.governmentForm = governmentForm;
        this.headOfState = headOfState;
        this.capital = capital;
        this.code2 = code2;
    }

    @Id
    @Column(name = "code")
    private String code;

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

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

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

    @Column(name = "surfacearea")
    private double area;

    @Column(name = "indepyear")
    private int year;

    @Column(name = "population")
    private int population;

    @Column(name = "lifeexpectancy")
    private double lifeExp;

    @Column(name = "gnp")
    private double gnp;

    @Column(name = "gnpold")
    private double gnpOld;

    @Column(name = "localname")
    private String localName;

    @Column(name = "governmentform")
    private String governmentForm;

    @Column(name = "headofstate")
    private String headOfState;


    @OneToOne(optional = false)
    @JoinColumn(name = "capital")
    private City capital;      //внимание сюда!!!

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

как видно вторая ссылается на первую. И проблем с сущностью Country как раз нет. Все поля в таблице заполняются. Проблема в первой сущности City, а конкретно с полем country - оно никак не отображается в таблицу, то есть в генерируемом хибернейтом запросе подстановка country не указана. Фрагмент Sql запроса:

Hibernate: 
    insert 
    into
        City
        (district, name, population, id) 
    values
        (?, ?, ?, ?)

то есть попросту не хватает параметра country. А так как в таблице он есть, ниже вылетает ексепшн мол нул в поле нотнул. Скорей всего не хватает аннотации какой то.

Собирается City следующим образом:

void createCity(City city,String code){
    manager.getTransaction().begin();
    city.setCountry(manager.find(Country.class,code));
    manager.persist(city);
    manager.getTransaction().commit();
}

String code - Это код страны которой будет принадлежать этот город. По нему из базы берется страна и подставляется конкретно в данный город.

3
  • конкретно что за ексепшн?
    – JVic
    22 ноя 2016 в 13:43
  • @Виктор org.postgresql.util.PSQLException: ERROR: null value in column "country" violates not-null constraint
    – Denis
    22 ноя 2016 в 13:45
  • а выше вот этот javax.persistence.RollbackException: Error while committing the transaction
    – Denis
    22 ноя 2016 в 13:46

1 ответ 1

2
package IntWorldDB.Entity;
import javax.persistence.*;

/**
 * Created by forpost on 05.11.16.
 */
@Entity
@NamedQuery(name="City.findByName",
            query="SELECT e FROM City e WHERE e.name = :name")
public class City {

    public City(){
    }

    @Id @GeneratedValue (strategy = GenerationType.IDENTITY )
    private int id;
    private String name;
    private String district;
    private int population;

    @ManyToOne (fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE})
    @JoinColumn(name = "countrycode", columnDefinition = "bpchar(3)", nullable = false)
    private Country country;

    /*геттеры и
......
 cеттеры*/
}

package IntWorldDB.Entity;
import javax.persistence.*;
import java.math.BigDecimal;

/**
 * Created by forpost on 05.11.16.
 */
@Entity

public class Country {

    public Country(){
    }

    @Id @Column(name = "code", columnDefinition = "bpchar(3)")
    private String code;


    private String name;
    private String continent;
    private String region;
    private Float surfacearea;
    @Column(columnDefinition = "int2")
    private Integer indepyear;
    private int population;
    private Float lifeexpectancy;
    private BigDecimal gnp;
    private BigDecimal gnpold;
    private String localname;
    private String governmentform;
    private String headofstate;

    @OneToOne
    @JoinColumn(name = "capital")
    private City city;

    @Column(name = "code2", columnDefinition = "bpchar(2)")
    private String code2;

    /*геттеры и
......
 cеттеры*/

}
1
  • Пожалуйста, постарайтесь писать более развернутые ответы. Уверен, автор вопроса был бы благодарен за ваш экспертный комментарий к приведенному выше коду. 23 ноя 2016 в 6:43

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.