开发者

Spring JPATemplate DAO. DELETE Items from table

News

@Entity
@Table(name = "NEWS")

@NamedQueries({
    @NamedQuery(name = "News.findAll", query = "SELECT n FROM News n"),
    @NamedQuery(name = "News.delete", query = "DELETE FROM News n WHERE n.newsId in(:ids)")
})

@GenericGenerator(name = "test-increment-strategy", strategy = "increment")
public class News implements Serializable {

    private static final long serialVersionUID = 3330980835510468207L;
    private Integer newsId;
    private String title;
    private String brief;
    private String content;
    private Date created;
    private String dateCreatedString;

    public News() {
    }

    @Id
    @Column(name = "NEWS_ID")
    // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq")
    // @SequenceGenerator(name = "news_seq", sequenceName = "NEWS_SEQ")
    @GeneratedValue(generator = "test-increment-strategy")
    public Integer getNewsId() {
        return newsId;
    }

DAO

@Override
@Transactional(readOnly = false)
public void removeNews(List<Integer> l开发者_StackOverflow社区istOfIdNewsForDeleting) throws DAOException {
    EntityManager entityManager = getJpaTemplate().getEntityManagerFactory().createEntityManager();

    Query query = entityManager.createNamedQuery("News.delete");
    query.setParameter("ids", listOfIdNewsForDeleting);
    int deleted = query.executeUpdate();
}

It's unsuccessful attempt delete news.

TransactionManager doesn't give transaction for new EntityManager which i call.

But i can't use query throw JpaTemplate. Have some idea?


The transaction manager does not start transactions for manually created entity managers. It only handles container/spring-managed entity managers. And without a transaction you can't delete.

The javadocs of JpaTemplate advise you to use the JPA-style data access. So use

@PersistenceContext 
private EntityManager entityManager;

(check the spring docs for what you need to enable it).

If you really want to huse the JpaTemplate then use only it, and don't get the underlying factory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜