Answer the question
In order to leave comments, you need to log in
How to use cascade='persist' with Hibernate and SQLite?
There is an obscure issue when using cascade='persist' in Hibernate + SQLite. We have data classes, Company and Person, connected by the @OneToMany relationship. In a simple application, we first create a Company object and store it in the database. Next, open a new session, load this Company object, add Person to it, and save Company. At the same time, Hibernate itself must cascade save the added Person. It's very simple, but I get an error:
ERROR: database is locked
Exception in thread "main" org.hibernate.exception.GenericJDBCException: error performing isolated work
@Entity
public class Company {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "company", cascade = { CascadeType.ALL })
private Set<Person> staff = new HashSet<>();
public void addPerson(Person person) {
if (staff.add(person)) {
person.setCompany(this);
}
}
public Set<Person> getStaff() {
return staff;
}
}
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Company company;
public void setCompany(Company company) {
this.company = company;
}
}
public class App {
public static void main(String[] args) {
createDatabase();
Company company;
Session session = createSessionFactory("validate").openSession();
company = (Company) session.createCriteria(Company.class).uniqueResult();
Person person = new Person();
company.addPerson(person);
session.beginTransaction();
session.persist(company);
session.getTransaction().commit();
session.close();
}
private static void createDatabase() {
Session session = createSessionFactory("create").openSession();
Company company = new Company();
session.beginTransaction();
session.persist(company);
session.getTransaction().commit();
session.close();
}
private static SessionFactory createSessionFactory(String ddl) {
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml");
serviceRegistryBuilder
.applySetting("hibernate.hbm2ddl.auto", ddl);
SessionFactory sessionFactory = new MetadataSources(serviceRegistryBuilder.build())
.buildMetadata()
.buildSessionFactory();
return sessionFactory;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question