我有一个表REPORT。此表与(例如)表CLIENT和表TAG有关系。
在请求中,我得到一个具有1-20客户端和1-20标签的报告。我需要在数据库中插入它(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最好用于数据结构不会改变的"稳定"数据库。