If someone could assist me in putting me back on track. I have a slight problem with using the Metamodel in helping with building queries.
Here are the relevent code snippets:
User.java
Code:
package votify.domain;
@Entity
@Table(name="VOTE_USER")
public class User implements Serializable {
public static final String PROP_NAME = "name";
public static final String PROP_CYCLESET = "cycleSet";
public static final String PROP_PWD = "pwd";
@Column(name="USERNAME", nullable=false)
protected String name;
UserMeta.java (I know the convention is User_.java)
Code:
package votify.domain;
@StaticMetamodel(User.class)
public class UserMeta {
public static volatile SingularAttribute<User, Long> id;
public static volatile SingularAttribute<User, String> name;
}
UserManager.java
Code:
1 package votify.manager;
.....
25 @Repository
26 public class UserManager implements Serializable {
27
28 @PersistenceContext(unitName = "VotifyPU")
29 private EntityManager em;
......
108 public User findUserByName(String username) {
109 CriteriaBuilder builder = em.getCriteriaBuilder();
110 CriteriaQuery<User> query = builder.createQuery(User.class);
111 Root<User> userRoot = query.from(User.class);
112 SingularAttribute<User, String> usernameAttr = UserMeta.name;
113// Path<String> aPath = userRoot.get("name");
114 Path<String> aPath = userRoot.get(UserMeta.name);
115 Expression<Boolean> isTrue = builder.equal(aPath, username);
116 query.select(userRoot);
117 query.where(isTrue);
118
119 TypedQuery<User> tQuery = em.createQuery(query);
120 User u = null;
121 try {
122 u = tQuery.getSingleResult();
123 } catch (Exception e) {
124 u = null;
125 }
126 return u;
127 }
UserManagerTest.java
Code:
1 package votify.manager;
134 @Test
135 public void findByName() {
136 String name = "Sizzle";
137 User user = userManager.findUserByName(name);
138 assertNotNull(user);
139 }
Output: (LogBack)
Code:
Testcase: findByName(votify.manager.UserManagerTest): Caused an ERROR
null
java.lang.NullPointerException
at org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:138)
at votify.manager.UserManager.findUserByName(UserManager.java:114)
at votify.manager.UserManagerTest.findByName(UserManagerTest.java:137)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
The weird thing is, if in the UserManager file, I comment out line 114 and instead use line 113, the test completes successfully.
I hope I have given enough information to solve this problem. (Or to say, "Hey, dummy, you forgot such and such.") :)