gpt4 book ai didi

java - 使用 Hibernate 玩 Framework - 如何像 Spring 一样使用 DAO/Service/controller

转载 作者:行者123 更新时间:2023-11-30 06:51:49 26 4
gpt4 key购买 nike

我有使用 Hibernate ORM 的 Spring 框架的经验。现在我正在尝试学习 Play Framework。我想将 Hibernate 用于 ORM。但我不知道该怎么做。

在 Spring 中,我使用这些类:

实体:

package com.example.test.entity;

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name="USERS")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

@Column(name="username")
private String username;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUsername() {
return username;
}
}

道:

package com.example.test.dao;

import java.util.List;
import com.example.test.entity.User;

public interface UserDao {
public void save(User user);
public void delete(User user);
public void update(User user);
public List<User> findAll();
public User findById(int id);
public User findByUserName(String username);
}


package com.example.test.dao;

import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.test.entity.User;

@Repository
public class UserDaoImpl implements UserDao {

@Autowired
private SessionFactory sessionFactory;

@Override
public void save(User user) {this.sessionFactory.getCurrentSession().save(user);}

@Override
public void delete(User user) {this.sessionFactory.getCurrentSession().delete(user);}

@Override
public void update(User user) {this.sessionFactory.getCurrentSession().update(user);}

@Override
public List<User> findAll() {
return this.sessionFactory.getCurrentSession().createQuery("from User").list();
}

@Override
public User findById(int id) {
return (User) this.sessionFactory.getCurrentSession().get(User.class, id);
}

@Override
public User findByUserName(String username) {
return (User) sessionFactory.getCurrentSession()
.createQuery("FROM User WHERE username = :username")
.setString("username", username).uniqueResult();
}
}

服务:

package com.example.test.service;

import java.util.List;
import com.example.test.entity.User;

public interface UserManager {
public void save(User user);
public void delete(User user);
public void update(User user);
public List<User> findAll();
public User findById(int id);
public User findByUserName(String username);
}


package com.example.test.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.test.dao.UserDao;
import com.example.test.entity.User;

@Service
@Transactional
public class UserManagerImpl implements UserManager {

@Autowired
private UserDao userDao;

@Override
public void save(User user) {userDao.save(user);}

@Override
public void delete(User user) {userDao.delete(user);}

@Override
public List<User> findAll() {return userDao.findAll();}

@Override
public User findById(int id) {return userDao.findById(id);}

@Override
public void update(User user) {userDao.update(user);}

@Override
public User findByUserName(String username) {
return userDao.findByUserName(username);
}
}

和 Controller :

package com.example.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.test.entity.User;
import com.example.test.service.UserManager;

@Controller
public class HomeController {
@Autowired
private UserManager userManager;

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
User u = userManager.findByUserName("admin@example.net");
model.addAttribute("user", u);
return "home";
}
}

我如何使用 Play+Hibernate 做到这一点?没有 @Service@Repository 注释。

我尝试在 Play 中使用相同的 Entity、DAO 和 Service 类。这是我的 Play 代码:

package controllers;

import com.avaje.ebean.Model;
import models.Person;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import service.PersonManager;
import javax.inject.Inject;
import java.util.List;
import views.html.index;

public class HomeController extends Controller {
@Inject
private PersonManager personManager;

public Result index() {return ok(index.render("Hello world"));}

@Transactional()
public Result getPersonByName(String name) {
Person p;
p = personManager.findByUserName("admin@example.net");
return ok(Json.toJson(p));
}
}

路由文件:

GET    /             controllers.HomeController.index

POST /person controllers.HomeController.addPerson()
GET /person/:id controllers.HomeController.getPersonByName(name)

应用程序.conf:

play.crypto.secret = "wtf"
play.i18n { langs = [ "en" ] }
play.db {
config = "db"
default = "default"
}
db {
default.driver = org.h2.Driver
default.url = "jdbc:h2:mem:play"
default.jndiName=DefaultDS
default.logSql=true
}
jpa {
default=defaultPersistenceUnit
}
ebean.default="models.*"

我在 build.sbt 中有 Hibernate:

libraryDependencies ++= Seq(
javaJpa,
"org.hibernate" % "hibernate-entitymanager" % "5.1.0.Final"
)

和 Hibernate persistence.xml:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
</properties>
</persistence-unit>
</persistence>

在我使用命令 $ activator ~run 启动应用程序后,它崩溃了:

...
[info] p.a.d.HikariCPConnectionPool - datasource [default] bound to JNDI as DefaultDS
[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:h2:mem:play
[info] application - ApplicationTimer demo: Starting application at 2016-10-05T22:06:14.913Z
[error] application -

! @71j15jjd7 - Internal server error, for (GET) [/] ->

play.api.UnexpectedException: Unexpected exception[ProvisionException: Unable to provision, see the following errors:

1) No implementation for service.PersonManager was bound.
while locating service.PersonManager
for field at controllers.HomeController.personManager(HomeController.java:24)
while locating controllers.HomeController
for parameter 1 at router.Routes.<init>(Routes.scala:44)
while locating router.Routes
while locating play.api.inject.RoutesProvider
while locating play.api.routing.Router
for parameter 0 at play.api.http.JavaCompatibleHttpRequestHandler.<init>(HttpRequestHandler.scala:200)
while locating play.api.http.JavaCompatibleHttpRequestHandler
while locating play.api.http.HttpRequestHandler
for parameter 4 at play.api.DefaultApplication.<init>(Application.scala:221)
at play.api.DefaultApplication.class(Application.scala:221)
while locating play.api.DefaultApplication
while locating play.api.Application

我谷歌了很多教程。但我无法修复它:-(

最佳答案

由于 PersonManager 是一个接口(interface),私有(private) PersonManager personManager 的 @Inject 注解是不够的。您应该指定什么类实现此接口(interface)。这是在 Spring 中做什么 @Service 注释。它在 Play 中的做法有所不同。

如果接口(interface)只有一个实现,你可以这样做:

@ImplementedBy(PersonManagerImpl.class)
interface PersonManager {
...
}

更灵活和推荐的方法是实现一个带有绑定(bind)的模块。 Play 默认模块类应命名为 Module,应按如下方式实现:

 public class Module extends AbstractModule {  
@Override
protected void configure() {
bind(PersonManager.class).to(PersonManagerImpl.class);
}
}

您可以在 Play here 中阅读有关依赖注入(inject)的更多信息.

关于java - 使用 Hibernate 玩 Framework - 如何像 Spring 一样使用 DAO/Service/controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39884570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com