source: mini_app_hibernate.zip(18kB)
This article continues from [Tapestry5HowToIocOnly] and adds tapestry-hibernate to the app.
Tapestry hibernate is currently dependant on tapestry-core (which will hopefully be fixed later).
We will add a dependancy to tapestry-core, but will not load whole TapestryModule.
Only some parts of the code will be provided in the page, and the rest as attachment.
For tapestry-hibernate to work without tapestry-core you need some extra setup in AppModule.
definitely make sure to call registry.cleanupThread(); at the end of the main method or your data will not be saved (tapestry-hibernate performs session.commit() when that event occurs)
1 public class MiniAppModule {
2
3 public static void bind(ServiceBinder binder){
4 binder.bind(Hello.class);
5 //tapestry-hibernate needs this dependency
6 binder.bind(ClassNameLocator.class, ClassNameLocatorImpl.class);
7 }
8
9 public static void contributeSymbolSource(OrderedConfiguration<SymbolProvider> conf){
10 //tapestry-hibernate fails without tapestry.app-name symbol defined
11 conf.add("AppPackage", new SymbolProvider(){
12 public String valueForSymbol(String symbolName){
13 if(symbolName.equalsIgnoreCase(InternalConstants.TAPESTRY_APP_PACKAGE_PARAM))
14 return "tapestry.mini";
15 return null;
16 }
17 },"");
18 }
19
20 public void contributeHibernateEntityPackageManager(Configuration<String> configuration)
21 {
22 // extra packages...
23 // tapestry-hibernate will add entities package automaticaly for TAPESTRY_APP_PACKAGE_PARAM+".entities"
24 // configuration.add("tapestry.mini.entities");
25 }
26 }
Hello class is bit different for this demo
1 public class Hello {
2
3 private final UserDao _userDao;
4
5 public Hello(UserDao userDao){
6 _userDao = userDao;
7 }
8
9 public void sayHello(){
10 List<User> list = _userDao.findAll();
11 if(list.size() == 0)
12 System.out.print("No users in database");
13 else
14 System.out.print("Hello "+list.get(0).getName());
15 }
16 }
User entity is just something simple
1 @Entity
2 public class User {
3
4 Long id;
5 String name;
6 String username;
7
8 public User(){}
9 public User(String name, String username) {
10 super();
11 this.name = name;
12 this.username = username;
13 }
14
15 @Id @GeneratedValue
16 public Long getId() {
17 return id;
18 }
19 //... other getters/setters
20 }
User dao just extends Generic Data Access Objects from http://www.hibernate.org
1 public class UserDAO extends GenericHibernateDAO<User, Long> {
2 //if you forget this constructor Session will not be injected
3 public UserDAO(Session session) {super(session);}
4
5 //example for search by criteria
6 public List<User> findByName(String name){
7 //findByCriteria is hibernate specific so you can not call _userDao.findByCriteria from
8 //outside this class, and you should not expose it either
9 return this.findByCriteria(Restrictions.eq("name", name));
10 }
11 }
run the app twice, first time it will create an user in the database, second time it will say Hello John.