简体   繁体   中英

Play Framework with Hibernate - how to Spring-like DAO/Service/controller

I have experience with Spring framework with Hibernate ORM. Now I'm trying to learn Play Framework. I would like to use Hibernate for ORM. But I do not know how to do that.

In Spring I use these classes:

Entity:

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;
    }   
}

DAO:

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();
    }
}

Service:

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);
    }    
}

and 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";
    }   
}

How can I do that with Play+Hibernate? There are no @Service and @Repository annotations.

I try in Play the same Entity, DAO and Service classes. There are my Play codes:

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));
    }
}

routes file:

GET    /             controllers.HomeController.index

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

application.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.*"

I have Hibernate in build.sbt :

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

And 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>

After I start app using command $ activator ~run , it crash:

...
[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

I google a lot of tutorials. But I can't fix it :-(

Since PersonManager is an interface, @Inject annotation of private PersonManager personManager is not sufficient. You should specify, what class implements this interface. This what is doing @Service annotation in Spring. It is done differently in Play.

In case the interface has a single implementation, you can just do this:

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

More flexible and recommended way is to implement a module with binding. Play default module class should be named Module and it should be implemented as following:

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

You can read more about dependency injection in Play here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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