我有以下实体:
@Entity
@Table(name="accounts")
public class AccountEntity extends TimestampAbstractEntity {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "id")
private int id;
}
TimestampAbstractEntity:
@MappedSuperclass
public abstract class TimestampAbstractEntity implements Serializable{
@Column(name = "created_at", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@Column(name = "updated_at", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
public Date getCreatedAt() {
return createdAt;
}
@PrePersist
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
@PreUpdate
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
Session中的delete方法根本不起作用,甚至没有显示日志。 我尝试使用
解决方法getCurrentSession().createQuery(delete from yadada where id=:id).setInteger("id", id).executeUpdate();
日志弹出弹出但数据库中没有任何反应,我使用的是hibernate-core 5.1.0.Final
我的配置是:
Configuration configuration = new Configuration();
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.current_session_context_class", "thread");
configuration.setProperty("hibernate.id.new_generator_mappings", "false");
configuration.setProperty("hibernate.show_sql", "true");
configuration.addAnnotatedClass(AccountEntity.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
return configuration.buildSessionFactory(builder.build());
答案 0 :(得分:0)
请你试试以下内容,告诉我你得到了什么结果?
public void deleteAccount(SessionFactory sessionFactory, Integer entityId) {
Session session = sessionFactory.getCurrentSession();
session.getTransaction().begin();
AccountEntity account = session.get(AccountEntity.class, entityId);
session.delete(account);
session.getTransaction().commit();
session.getTransaction().begin();
account = session.get(AccountEntity.class, entityId);
System.out.println(account); //Should be null!
session.getTransaction().rollback();
}
或者如果您想使用查询:
public void deleteAccount(SessionFactory sessionFactory, Integer entityId) {
Session session = sessionFactory.getCurrentSession();
session.getTransaction().begin();
session.createQuery("delete from AccountEntity where id=:id").setInteger("id", id).executeUpdate();
session.getTransaction().commit();
session.getTransaction().begin();
account = session.get(AccountEntity.class, entityId);
System.out.println(account); //Should be null!
session.getTransaction().rollback();
}