【问题标题】:What is the best way to update data in database using Native Query使用本机查询更新数据库中数据的最佳方法是什么
【发布时间】:2021-01-28 00:50:16
【问题描述】:
    EntityManager em = entityManagerFactory.createEntityManager();
    String str = String.format("UPDATE service.rules SET server_id='%2$s', alert_id='%3$s', rule_expression='%4$s', rule_frequncy='%5$s' WHERE rule_id='%1$s'",Rule.getRuleId(),Rule.getServerId(),Rule.getAlertId(),Rule.getRuleExpression(),Rule.getRuleFrequency());
    Query query = em.createNativeQuery(str);
    em.getTransaction().begin();
    query.executeUpdate();
    em.getTransaction().commit();

在这里,如果规则对象中的一个数据除了 rule_id 之外为空(如果有必要),则此查询将失败,因此我可以为 Rule 对象中的每个值格式化字符串并将它们连接起来,排除在 Rule 对象中具有空值但有没有更好的方法来做到这一点?因为如果有 100 列,那么这将不是理想的过程。 JPA 也有任何可以满足我要求的东西。

【问题讨论】:

    标签: java sql spring-boot jpa spring-data-jpa


    【解决方案1】:

    JPA 的做法是创建实体映射:

    @Entity
    public class Rule {
        @Id
        private int id;
    
        @ManyToOne
        private Server server;
    
        @OneToOne
        private Alert alert;
    
        private String ruleExpression;
    
        private double ruleFrequency;
    }
    

    一个 spring jpa 存储库:

    @Repository
    class RuleRepository extends JpaRepository<Rule, Integer> {
    }
    

    还有一个处理持久性的服务:

    @Service
    public class RuleService {
        @Autowired RuleRepository ruleRepository;
    
        @Transactional
        public Rule update( Rule rule ) {
            return ruleRepository.save( rule );
        }
    }
    

    并像这样使用它:

    Rule rule = getRule();
    //change rule
    ruleService.update(rule);
    

    JPA 提供程序将在幕后为您生成查询,无需复杂的原生查询。

    【讨论】:

    • 谢谢,我试试这个。我已经有 Entity 但没有使用,因为我是 Spring Boot 新手,对此并不陌生。
    猜你喜欢
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多