说明: 删除与更新用的方法类似,这里仅以更新数据为例。

方法一,Play!封装的JPA:
查询后,直接更新字段并保存

long id = 1;
DogEntity entity = DogEntity.findById(id);
entity.name = "Mike";
entity.color = "brown";
entity.save();

方法二, 原生JPA—JPA.em().createQuery(sql).executeUpdate():

        String sql = "update DogEntity set " +
                "name ='Mike', color = 'brown' " +
                "where id = 1";
 int count = JPA.em().createQuery(sql).executeUpdate();
 logger.info("删除个数:" + count);

方法三, JDBC—pstmt.executeUpdate():

String sql = "update DogEntity set " +
                "name = ?, color = ?, +
                "where id = ?";
        logger.debug(sql);
        Connection conn = null;
        PreparedStatement pstmt=null;
        boolean flag = false;
        try {
            conn = DBTool.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
            DBTool.close(null, pstmt, conn);
            logger.info("数据库连接出错");
        }

        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"Mike");
            pstmt.setString(2, "brown");
            pstmt.setLong(3, 1);
            int count = pstmt.executeUpdate();
            logger.debug("更新条数:" + count);
            flag = true;
        } catch (SQLException e) {
            e.printStackTrace();
            logger.info("SQL语句出错");
        }finally{
            DBTool.close(null, pstmt, conn);
        }
        return flag;
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐