我正在使用spring roo进行我的一个项目。 spring roo的作用是为现有类添加持久性方法。例如,您可以调用Person.persist()来保存数据库中person类型的对象。
我最近看到了另一种模式。以下是代码。
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
@Repository
public class CustomerRepository {
@PersistenceContext
private EntityManager em;
@Transactional
public void save(Customer c) {
em.persist(c);
}
}
@Controller
public class HomeController {
@Autowired
CustomerRepository customerRepository;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
* @throws Exception
*/
@Transactional
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home controller! The client locale is {}.", locale);
Customer c = new Customer("XXX", "YYY");
customerRepository.save(c);
return "home";
}
}
每种方法的优点和缺点是什么?