繁体   English   中英

将数据插入具有多列的关系表的最佳实践(无 ORM)

[英]Best practice for insert data into relation table with many columns (no ORM)

我有表报告。 该表与(例如)表 CLIENT 和表 TAG 有关系。

在请求中,我收到一份带有 1-20 CL​​IENT 和 1-20 TAG 的报告。 我需要将它插入数据库(postgre)。

如果我只能使用 JdbcTemplate,我该怎么做? (禁止所有 ORM)。 当然有事务和回滚? 我只需要一些想法。

报表模型类

@Entity
@Table(name = "reports")
public class Report {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    @OneToMany(mappedBy="report")
    private List<Client> clients;

    @OneToMany(mappedBy="report")
    private List<Tag> tags;
}

客户模型类

@Entity
@Table(name = "clients")
public class Client {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
    @JoinColumn(name = "report_id")
    private Report report;
}

标签模型类

@Entity
@Table(name = "tags")
public class Tag {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String tagName;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
    @JoinColumn(name = "report_id")
    private Report report;
}

报表控制器

Report report = new Report();
        report.setName("Report");

        List<Client> clientList = new ArrayList<>();
        Client client1 = new Client();
        client1.setName("user1");
        Client client2 = new Client();
        client2.setName("user2");
        clientList.add(client1);
        clientList.add(client2);

        List<Tag> tagList = new ArrayList<>();
        Tag tag1 = new Tag();
        tag1.setTagName("tag1");
        tagList.add(tag1);

        report.setClients(clientList);
        report.setTags(tagList);

        Report resultReport = reportRepository.save(report);

以此作为参考,它会起作用。

避免 ORM,前进的方法是使用 JDBCTemplate,我假设它将被注入下面的 3 个 @Repositories:

@Repository
public class TagRepository {

    public void insertreport(Report report) {
        .. do an insert using @JdbcTemplate
    }

}

@Repository
public class TagRepository {

    public void insertTags(List<Tag> tags) {
        .. do a bulk insert using @JdbcTemplate
    }   

}

@Repository
public class ClientRepository {

    public void insertClients(List<Client> clients) {
        .. do a bulk insert using @JdbcTemplate
    }

}

@Service
public class ReportService {

    @Autowire 3 @Repository above

    @Transactional
    public void addReport(Report report) {
        reportRepository.insertReport(report);
        tagRepository.insertTags(report.getTags());
        clientRepository.insertClients(report.getClients());
    }

}

相当冗长的代码,但是拆分成@Repositories 合理的封装可以让它变得可以忍受。

请注意:JdbcTemplate 最适合用于数据结构不会改变的“稳定”数据库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM