Hibernate filters are not working for APIs returning single result - database

I have added Hibernate filters on my entities . These filters are applied on queries which fetch Collection of entity but not applied on queries which fetch single entity. Below is my code.
AOrganization.java
#MappedSuperclass
#FilterDef(name = "OrgFilter", parameters = { #ParamDef(name = "allowedOrgIdList", type = "long") })
#Filter(name = "OrgFilter", condition = "org_id in (:allowedOrgIdList)")
public class AOrganization implements Serializable {
#ManyToOne()
#JoinColumn(name = "org_id", nullable = true)
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Site.java
#Data
#Entity
#Table(name = "site")
public class Site extends AOrganization{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "site_name")
private String siteName;
#Override
public String toString() {
return "Site [id=" + id + ", siteName=" + siteName + "]";
}
}
SiteService.java
public interface SiteService {
public List<Site> getAllSites();
public List<Site> getSiteBySiteName(String siteName);
public Site updateSiteName(Long id, String siteName);
}
SiteRepository.java
#Repository
public interface SiteRepository extends AOrganizationRepository<Site, Long> {
public List<Site> findBySiteName(String siteName);
public List<Site> findByOrganization_Id(Long orgId);
}
AOrganizationRepository.java
#NoRepositoryBean
public interface AOrganizationRepository<T, ID extends java.io.Serializable> extends CrudRepository<T, ID> {
}
SiteServiceImpl.java
#Service
public class SiteServiceImpl implements SiteService {
#Autowired
private EntityManager entityManager;
#Autowired
private SiteRepository siteRepository;
#Override
public List<Site> getAllSites() {
Iterable<Site> sites = siteRepository.findAll();
List<Site> allSites = new ArrayList<>();
sites.forEach(allSites::add);
return allSites;
}
#Override
public List<Site> getSiteBySiteName(String siteName) {
List<Site> allSites = siteRepository.findBySiteName(siteName);
return allSites;
}
#Override
public Site updateSiteName(Long id,String siteName) {
Site site = siteRepository.findById(id).get();
if(site == null)
return null;
site.setSiteName(siteName);
siteRepository.save(site);
return site;
}
}
AOrganizationAspect.java
#Aspect
#Component
#Slf4j
public class AOrganizationAspect {
#PersistenceContext
private EntityManager entityManager;
#Pointcut("execution(public * com.harshal.springboot.springfilter.repository.AOrganizationRepository+.*(..))")
protected void aOrganizationRepositoryRepositoryMethod() {
log.info("aOrganizationRepositoryRepositoryMethod");
}
#Around(value = "aOrganizationRepositoryRepositoryMethod()")
public Object enableOwnerFilter(ProceedingJoinPoint joinPoint) throws Throwable {
// Variable holding the session
Session session = null;
try {
// Get the Session from the entityManager in current persistence context
session = entityManager.unwrap(Session.class);
// Enable the filter
Filter filter = session.enableFilter("OrgFilter");
// Set the parameter from the session
List<Long> orgList = getAllowedOrgIdList();
filter.setParameterList("allowedOrgIdList", orgList);
} catch (Exception ex) {
// Log the error
log.error("Error enabling OrgFilter : Reason -" + ex.getMessage());
}
// Proceed with the joint point
Object obj = joinPoint.proceed();
// If session was available
if (session != null) {
// Disable the filter
session.disableFilter("OrgFilter");
}
// Return
return obj;
}
private List<Long> getAllowedOrgIdList() {
return Arrays.asList(2l);
}
}
So , hibernate filters are applied if method getSiteBySiteName is called and filters are not applied if findById method is called.
Below are queries :
For getSiteBySiteName :
select site0_.id as id1_2_, site0_.org_id as org_id3_2_,
site0_.site_name as site_nam2_2_ from site site0_ where site0_.org_id
in (?) and site0_.site_name=?
Please help . Thanks in advance.
For findById
select site0_.id as id1_2_0_, site0_.org_id as org_id3_2_0_,
site0_.site_name as site_nam2_2_0_, organizati1_.id as id1_1_1_,
organizati1_.address as address2_1_1_, organizati1_.org_name as
org_name3_1_1_ from site site0_ left outer join organization
organizati1_ on site0_.org_id=organizati1_.id where site0_.id=?

findById is using the EntityManager.find method and do not create a query.
Plus Hibernate Filters only work on queries.
You should write a query instead of using findById

Related

How do I delete multiple records using REST API

Am new to Springboot, I have develop the resource to delete the record by ID, now I like delete selected multiple records.
Example: I like to delete 3 records out of 10 records in single request
Controller class:
#ApiHeader(
apiOperation = "delete a Content Manage by id",
apiOperationNotes = "delete a Content Manage by id"
)
#PostMapping(value = UriConstants.CONTENT_MANAGE_DELETE)
#ResponseStatus(HttpStatus.OK)
public void deleteContentManage(#PathVariable("content_manage_id") int contentmanageId) {
contentManageService.deleteContentManage(contentmanageId);
}
Service Class:
#Transactional(rollbackFor = Exception.class)
public void deleteContentManage(int contentmanageId) {
Optional<UserContentManage> optional = userContentManageRepository.findById(contentmanageId);
if(!optional.isPresent()){
log.error("Exception occurs while not found content manage ({}) in deletion. ", contentmanageId);
throw new GenericBadException(StaffNotificationExceptionEnum.CONTENT_MANAGE_NOT_FOUND_EXCEPTION);
}
userContentManageRepository.deleteById(contentmanageId);
}
JPA Class:
public interface UserContentManageRepository extends JpaRepository<UserContentManage, Integer> {
}
please suggest me how do I delete selected multiple records.
You can add method in Repository like
#Modifying
#Transactional
#Query("delete from UserContentManagep where u.id in(:integers)")
void deleteByIdIn(List<Integer> integers);
If you have implemented soft delete in project you can do soft delete like below:
#Modifying
#Transactional
#Query("update UserContentManagep u set u.active = false where u.id in(:integers)")
void softDeleteAllIds(List<Integer> integers);
And from service class you can try to call as
public void deleteAllBYIds(List<Integer> integers) {
personRepository.deleteByIdIn(integers);
}
Fully working example:
#RestController
#RequestMapping("/person")
public class PersonController {
private final PersonService personService;
#Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
#GetMapping
public Iterable<Person> list() {
return personService.list();
}
#PostMapping
public Person create(#RequestBody Person car) {
return personService.save(car);
}
#DeleteMapping
public String delete(#RequestParam("ids") List<Integer> ids) {
System.out.println("deleting");
personService.deleteAllBYIds(ids);
return String.join(",", ids.stream().map(value -> Integer.toString(value)).collect(Collectors.toList()));
}
}
#Getter
#Setter
#ToString
#Entity
#Where(clause = "active = true") // selecting only items which are active
class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private boolean active = true;
}
#Service
class PersonService {
private final PersonRepository personRepository;
#Autowired
PersonService(PersonRepository personRepository) {
this.personRepository = personRepository;
}
#Transactional
public Person save(Person person) {
return personRepository.save(person);
}
#Transactional(readOnly = true)
public Iterable<Person> list() {
return personRepository.findAll();
}
#Transactional(readOnly = true)
public PersonDTO findPersonByName(String name) {
return personRepository.findPersonsByName(name);
}
public void deleteAllBYIds(List<Integer> integers) {
// personRepository.deleteByIdIn(new ArrayList<>(integers));
personRepository.softDeleteAllIds(integers);
System.out.println("deleted adnlakdjakldlas");
}
}
interface PersonDTO {
String getName();
Collection<String> getPersonEvents();
}
#Repository
interface PersonRepository extends CrudRepository<Person, Integer> {
PersonDTO findPersonsByName(String name);
#Modifying
#Transactional
#Query("delete from Person p where p.id in(:integers)")
void deleteByIdIn(List<Integer> integers);
#Modifying
#Transactional
#Query("update Person p set p.active = false where p.id in(:integers)")
void softDeleteAllIds(List<Integer> integers);
}
First of all you need to create a jpa query method that brings all records belong to id.
public interface UserContentManageRepository extends JpaRepository<UserContentManage, Integer> {
List<UserContentManage> findAllById(Integer id);
}
After that you can do deleteAll() operation on List.
#Transactional(rollbackFor = Exception.class)
public void deleteContentManage(int contentmanageId) {
List<UserContentManage> userContentManageList = userContentManageRepository.findAllById(contentmanageId);
if(userContentManageList == null){
log.error("Exception occurs while not found content manage ({}) in deletion. ");
throw new GenericBadException(StaffNotificationExceptionEnum.CONTENT_MANAGE_NOT_FOUND_EXCEPTION);
}
userContentManageRepository.deleteAll(userContentManageList );
}

Can't properly display data in tableView in JavaFX

I was trying to add data to my tableView in my JavaFX app. I am using hibernate to do operations on my Database. I used a query to get all the orders and store each order in an object and added the object to the observable list of the tableView. I created the orders class and mapped it to my database. This is the class of the orders:
#Entity
#Table(name = "orders")
public class orders implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "order_id")
private int order_id;
#JoinColumn(name = "item_id")
#ManyToOne
#NotNull
private items item_id;
#Column(name = "quantity")
#NotNull
private int quantity;
#Column(name = "price_per_unit")
#NotNull
private double price_per_unit;
#Column(name = "total_price")
#NotNull
private double total_price;
#Column(name = "order_date")
#NotNull
private Date order_date;
#JoinColumn(name = "user_id")
#ManyToOne
#NotNull
private users user_id;
public orders() {
}
public orders(int order_id, items item_id, int quantity, double price_per_unit, double total_price, Date order_date, users user_id) {
this.order_id = order_id;
this.item_id = item_id;
this.quantity = quantity;
this.price_per_unit = price_per_unit;
this.total_price = total_price;
this.order_date = order_date;
this.user_id = user_id;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public items getItem_id() {
return item_id;
}
public void setItem_id(items item_id) {
this.item_id = item_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice_per_unit() {
return price_per_unit;
}
public void setPrice_per_unit(double price_per_unit) {
this.price_per_unit = price_per_unit;
}
public double getTotal_price() {
return total_price;
}
public void setTotal_price(double total_price) {
this.total_price = total_price;
}
public Date getOrder_date() {
return order_date;
}
public void setOrder_date(Date order_date) {
this.order_date = order_date;
}
public users getUser_id() {
return user_id;
}
public void setUser_id(users user_id) {
this.user_id = user_id;
}
}
And the below code is the code of the view in which I have the tableView that loads the orders and displays the orders from the database:
public class OrdersPageController implements Initializable {
private Main app;
private Session session;
private Transaction transaction = null;
#FXML
private TableView<orders> table;
public void setApp(Main app) {
this.app = app;
}
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
//Fill the table view
getOrders();
}
public void goBack(ActionEvent event){
session.close();
transaction = null;
app.goToHomePage();
}
public void processLogout(ActionEvent event){
session.close();
transaction = null;
app.userLogout();
}
public void addOrder(ActionEvent event){
session.close();
transaction = null;
app.addOrdersPage();
}
public void deleteOrder(ActionEvent event){
session.close();
transaction = null;
app.closeOrdersPage();
}
public void getOrders(){
try{
String hql = "FROM orders";
Query query = session.createQuery(hql);
List<orders> list = query.getResultList();
for (orders o : list) {
//Create an order object
orders order = new orders();
order.setOrder_id(o.getOrder_id());
order.setItem_id(o.getItem_id());
order.setPrice_per_unit(o.getPrice_per_unit());
order.setQuantity(o.getQuantity());
order.setOrder_date(o.getOrder_date());
order.setTotal_price(o.getTotal_price());
order.setUser_id(o.getUser_id());
//Create an observable list for the table
ObservableList<orders> tableList = table.getItems();
//Add the order object to the list
tableList.add(order);
//Set the created list to the table to show data
table.setItems(tableList);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.close();
}
}
}
Note that the getOrders method is the method that gets the orders from the database and sets the observable list of the tableView.
I am having problem displaying the item_id and the user_id of the order. I think the problem is that they both are objects of type items and users respectively and the table displays the address of the objects. Instead I want to display the numbers of the ids of the item ordered and the user that made the order. If you know what I can do to fix my problem please share it with me.
Add cellFactorys to the relevant columns. You haven't shown the FXML in the question, so I don't know the names you assigned to the appropriate TableColumn instances, but you can do something like this:
public class OrdersPageController implements Initializable {
// ...
#FXML
private TableView<orders> table;
#FXML
private TableColumn<orders, users> userColumn ;
#Override
public void initialize(URL url, ResourceBundle rb) {
userColumn.setCellFactory(tc -> new TableCell<>() {
#Override
protected void updateItem(users user, boolean empty) {
super.updateItem(user, empty);
if (empty || user == null) {
setText("");
} else {
String text = /* anything you need based on user */
setText(text);
}
}
});
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
//Fill the table view
getOrders();
}
}
Just override toString method in users and items Classes:
Example: in your users Class ->
#Override
public String toString() {
return user_id.toString();
}
As James_D stated, have a look on java conventions. Java Classes should be always be with Capital Letter.

MappingException: Ambiguous field mapping detected

Using Spring boot 1.5.6.RELEASE.
I have the following mongo document base class:
#Document(collection="validation_commercial")
public abstract class Tier {
#Id
private String id;
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date created;
#Field("tran")
private Tran tran;
public Tier() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Tran getTran() {
return tran;
}
public void setTran(Tran tran) {
this.tran = tran;
}
}
which is then extended:
public class Tier1 extends Tier {
#Field("tier1")
private Tier1Programs tier1;
public Tier1() {
this.tier1 = new Tier1Programs();
}
public Tier1Programs getTier1() {
return tier1;
}
public void setTier1(Tier1Programs tier1) {
this.tier1 = tier1;
}
}
which in turn is extended:
public class Tier2 extends Tier1 {
#Field("tier2")
private Tier2Programs tier2;
public Tier2() {
this.tier2 = new Tier2Programs();
}
public Tier2Programs getTier2() {
return tier2;
}
public void setTier2(Tier2Programs tier2) {
this.tier2 = tier2;
}
}
There is a Tier1 Supervisor (Spring Boot Application) that uses the Tier1 class within the MongoRepository interface:
public interface Tier1Repository extends MongoRepository<Tier1,String>{}
for retrieving and saving - no issue.
I then have a Tier2 Supervisor (Spring Boot Application) that uses a Tier1 Repository (for retrieving the Tier1 document and a Tier2 Repository for saving the Tier2 document:
#Repository("tier1Repository")
public interface Tier1Repository extends MongoRepository<Tier1,String>{}
#Repository("tier2Repository")
public interface Tier2Repository extends MongoRepository<Tier2,String>{}
My service is:
#Service
public class TierService {
#Qualifier("tier1Repository")
#Autowired
private final Tier1Repository tier1Repository;
#Qualifier("tier2Repository")
#Autowired
private final Tier2Repository tier2Repository;
public TierService(#Qualifier("tier1Repository") Tier1Repository tier1Repository, #Qualifier("tier2Repository") Tier2Repository tier2Repository) {
this.tier1Repository = tier1Repository;
this.tier2Repository = tier2Repository;
}
public Tier1 findOne(String id) {
return tier1Repository.findOne(id);
}
public void SaveTier(Tier2 tier) {
tier2Repository.save(tier);
}
public Tier1Repository getTier1Repository() {
return tier1Repository;
}
public Tier2Repository getTier2Repository() {
return tier2Repository;
}
}
and finally the app:
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class})
#Configuration
#ComponentScan(basePackages = {"com.k12commercial.tier2supervisor"})
#ImportResource("classpath:application-context.xml")
public class Application implements CommandLineRunner {
#Autowired
private IReceiver raBidNetPriceReceiver;
#Autowired
private UdyDataSourceFactory udyDSRegistry;
public static void main(String[] args) throws InterruptedException {
try {
SpringApplication.run(Application.class, args);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run(String... args) throws Exception {
raBidNetPriceReceiver.processTierMessages();
exit(0);
}
}
When I run the Tier2 Supervisor from the command line I get the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'tierService' defined in URL
[jar:file:/opt/java-commandline/tier2supervisor-1.0.jar!/BOOT-INF/classes!/com/k12commercial/tier2supervisor/service/TierService.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tier2Repository': Invocation of init method failed; nested exception is org.springframework.data.mapping.model.MappingException: Ambiguous field mapping detected! Both private final java.lang.reflect.Type org.springframework.data.util.TypeDiscoverer.type and private final java.lang.Class org.springframework.data.util.ClassTypeInformation.type map to the same field name type! Disambiguate using #Field annotation!
I am not sure if the issue is Tier2 extending Tier1 (did try putting #Document tag above Tier1 and Tier2 with no change). I think I have marked the relevant fields so don't understand the need to disambiguate. I thought the issue was having 2 repositories (Spring Boot not knowing which one to DI) so removed the Tier1Repository - didn't work. Tried better qualifying the repositories but still got the same error. I made Tier1 and Tier2 #Transient and that got rid of the message but also removed the tier1 section in the mongo document - so wrong correction.
Thinking it is an annotation fix but not seeing it...
Please advise - thank you.
Sorry for the delay (I got pulled away to work on something else) and thank you to those who responded.
The issue was I had a MongoTemplate in my Tier level programs e.g.Tier2Programs (sub library) which Spring Boot was trying to autowire.
By moving the Mongo (CRUD) requirements to the supervisor level (I also replaced the Repositories with one MongoTemplate to simplify) I removed the ambiguity. (I also removed the Service class).
The code is contained with the RaBidNetReciever class
#Component
public class RaBidNetPriceReceiver extends BaseReceiver implements IReceiver, ApplicationEventPublisherAware {
private static final Logger LOGGER = LoggerFactory.getLogger(RaBidNetPriceReceiver.class);
private final RabbitTemplate raBidNetPriceRabbitTemplate;
public RaBidNetPriceReceiver(MongoTemplate mongoTemplate, RabbitTemplate raBidNetPriceRabbitTemplate) {
super(mongoTemplate);
this.raBidNetPriceRabbitTemplate = raBidNetPriceRabbitTemplate;
}
#Transactional
public void processTierMessages() {
try {
while (true) {
gson = getGsonBuilder().create();
byte[] body = (byte[]) raBidNetPriceRabbitTemplate.receiveAndConvert();
if (body == null) {
setFinished(true);
break;
}
tier1Message = gson.fromJson(new String(body), Tier1Message.class);
// document a 'Tier1' type so retrieve Tier1 first...
Tier1 tier1 = mongoTemplate.findById(tier1Message.getId(), Tier1.class);
Tier2Message tier2Message = new Tier2Message(tier1Message.getTran(), tier1Message.getId());
Tier2Process tierProcess = getTierProcess(tier2Message.getTran().getK12ArchitectureId());
Tier2 tier2 = new Tier2();
tier2.setId(tier1.getId());
tier2.setTier1Programs(tier1.getTier1Programs());
tier2.setCreated(tier1.getCreated());
tier2.setTran(tier1.getTran());
tierProcess.setTier(tier2);
tier2 = tier2.getTier2Programs().getRaBidNetPriceProgram().process(tierProcess);
mongoTemplate.save(tier2);
if (tier2.getTier2Programs().getRaBidNetPriceProgram().isFinished()) {
// publish event
publisher.publishEvent(new ProgramEvent(this, "FINISHED", tier2Message));
}
}
} catch (Exception e) {
LOGGER.error("id: " + tier1Message.getId() + " " + e.getMessage());
}
}
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
}
Thank you,

Trouble persisting one-to-many relationship using jpa in Google app engine

I have two entities as below and when i try to persist "Category" the "Tip" object list does not get persisted .I noticed that in my DAO class that I was able to see the category object with tipsForCategory list of size 1 but when i try to retrieve after persisting I am able to see only Category details and tipsForCategory comes as empty list.
#Entity
public class Category {
#GeneratedValue
#Id
public Long id;
#Column
public String categoryName;
#OneToMany(mappedBy = "category",cascade = {CascadeType.ALL})
public List<Tip> tipsForCategory;
public Long getId() { return id; }
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName.toLowerCase();
}
public void addTip(Tip tip) {
if(!tipsForCategory.contains(tip)) {
tipsForCategory.add(tip);
}
}
public List<Tip> getTipsForCategory() {
return tipsForCategory;
}
}
Code for Tip Entity
#Entity
public class Tip {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Key key;
#Column
public String tipDescription;
#ManyToOne(cascade = {CascadeType.ALL})
public Category category;
public String getTipDescription() {
return tipDescription;
}
public void setTipDescription(String tipInformation) {
this.tipDescription = tipInformation;
}
}
Code for persisting in my DAO
#Override
#Transactional
public void save(Category category) {
EntityManager localEntityManager=entityManager.getEntityManagerFactory().createEntityManager();
EntityTransaction transaction=localEntityManager.getTransaction();
try {
transaction.begin();
localEntityManager.persist(category);
localEntityManager.flush();
transaction.commit();
}catch (Exception e) {
e.printStackTrace();
localEntityManager.close();
}
}
My retrieval method is
#Override
public CategoryDTO findCategory(Long categoryId) throws FixitException{
CategoryDTO categoryDTO=null;
Category category=categoryDAO.findById(categoryId);
if(category!=null) {
categoryDTO=new CategoryDTO(category);
}
return categoryDTO;
}
#Override
public List<TipDTO> retrieveTips(Long categoryId) throws FixitException{
List<TipDTO> tips=null;
try {
CategoryDTO category = findCategory(categoryId);
if (category != null) {
tips = category.getTipsForCategory();
}
}
catch(Exception e)
{
throw new FixitException(FixitConstants.TIP_RETRIEVAL_ERROR+categoryId,e.getCause());
}
return tips;
}
Looks like the problem was with lazy fetch I just resolved the same.In my categoryDAO.findById(..) code I had to add an additional line to retrieve the tips as below
#Override
public Category findById(Long categoryId) {
Category category=null;
try {
TypedQuery<Category> findByCategoryId = entityManager.createQuery("Select cat from Category cat where cat.id=:categoryId",Category.class);
category=findByCategoryId.setParameter("categoryId", categoryId).getSingleResult();
}
catch (Exception e)
{
e.printStackTrace();
}
*** int tipsSize=category.getTipsForCategory().size();***
return category;
}

GAE GWT JDO persistent List<Element> does not save/load correctly

I'm worring about JDO in GAE (Google App Engine). (GWT 2.4 and GAE 1.6.3 SDK and JDO 2.3)
I have a class "Users" which should save a Collection of "User" in a List, but it doesn't work.
When i save my Users-Class, then it creates the "Users"-Object in the Datebase and it also creates the User-Object in the List users. But when i load the Users-Object from the Database, the List users is empty...
Do i have to load the list by my self? I guess that JDO schould load the list directy, when i load the Users-Object.
I need your Help here! Thanks in previous!
Could it be a Problem that i create the Key in abstract class PersistentUser and PersistentUsers?
Could the LinkedList be the Problem?
My Code:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
#Version(strategy=VersionStrategy.VERSION_NUMBER)
public class Users extends PersistentUsers implements Serializable{
/**
*
*/
private static final long serialVersionUID = -21666269538993247L;
/**
* Mapped from Operator X
*/
#Persistent
private String operatorId;
#Persistent(mappedBy="userlist")
#Element(dependent = "true")
private List<User> users;
/**
*
* List of Ids of Users
*
*/
#Persistent(serialized = "true")
#Element(dependent = "true")
private List<String> userIds;
/**
* #return the users
*/
public List<User> getUsers() {
return users;
}
/**
* #param users the users to set
*/
public void setUsers(List<User> users) {
this.users = users;
}
...
}
The User Class:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
#Version(strategy=VersionStrategy.VERSION_NUMBER)
public class User extends PersistentUser implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6899284258473985914L;
#Persistent
private String emailAddress;
#Persistent
private UserRole role;
/**
*
* Mapped from Userlist X from Operator Y
*/
#Persistent
private Users userlist;
public User(String email, UserRole role){
this.emailAddress = email;
this.role = role;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
/**
* #return the userlist
*/
public Users getUserlist() {
return userlist;
}
/**
* #param userlist the userlist to set
*/
public void setUserlist(Users userlist) {
this.userlist = userlist;
}
}
PersistentUser and PersistentUsers Class are the same content (but because of JDO-AppEngine Inheritance Problem two seperate classes:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
#Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
#Version(strategy=VersionStrategy.VERSION_NUMBER)
public abstract class PersistentUsers implements IPersitentObject {
/**
* Id
*
* Autogenerated String id of the Database
*
*/
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
protected Key encodedKey;
#Persistent
protected String username;
#Override
public String getId() {
if(encodedKey == null) return null;
return KeyFactory.keyToString(encodedKey);
}
/*public void setId(String id) {
this.encodedKey = id;
}*/
/**
* Helper function - get Version from DB
*/
#Override
public Long getVersion(){
...
}
/**
* Helper function - will save this instance in DB
*/
public void persist(){
...
}
/**
* Helper function - will remove this instance from DB
*/
public void delete(){
...
}
#Override
public final boolean checkUsername() {
...
}
}
Create User Code:
...
if(RequestFactoryServlet.getThreadLocalRequest().getUserPrincipal() != null){
//Create New User
String email = RequestFactoryServlet.getThreadLocalRequest().getUserPrincipal().getName();
User u = UserFactory.getUser(email, UserRole.ADMINISTRATOR);
//u.persist();
//Create New Userlist
Users users = UserFactory.getUsers();
//Get Uids (normally empty)
LinkedList<String> uids = (LinkedList<String>) users.getUserIds();
if(uids==null){
uids = new LinkedList<String>();
}
uids.add(u.getId());
//Get DB-Userlist of current User-List
LinkedList<User> userlist = (LinkedList<User>) users.getUsers();
if(userlist==null){
userlist = new LinkedList<User>();
}
userlist.add(u);
users.setUserIds(uids);
users.setUsers(userlist);
u.setUserlist(users);
//Persit Userlist and Persist User
users.persist();
this.userlistId = users.getId();
}
...
Persistence Code:
public static void persist(IPersitentObject o){
PersistenceManager pm = Pmf.get().getPersistenceManager();
try{
pm.makePersistent(o);
} catch (Exception e) {
e.printStackTrace();
}finally {
pm.close();
}
}
I found the problem/solution
It's my stupid brain thinking i could fetch it while debugging.
My code is correct, but the information is not in the object while debugging!
Test it in a TestCase showed, that it works.
public class UsersTest {
private PersistenceManager pm;
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private String userlistId;
private String userId;
#Before
public void setUp() throws Exception {
helper.setUp();
pm = ch.zhaw.ams.server.core.persistance.Pmf.get().getPersistenceManager();
}
#After
public void tearDown() throws Exception {
}
#Test
public void testNewUsers() {
//New UserList
//Create New Userlist
Users users = UserFactory.getUsers();
//Create New User
String email = "ss";
User u = UserFactory.getUser(email, UserRole.ADMINISTRATOR);
users.getUsers().add(u);
users.persist();
this.userlistId = users.getId();
this.userId = users.getUsers().get(0).getId();
//Test Users
pm = ch.zhaw.ams.server.core.persistance.Pmf.get().getPersistenceManager();
Users ul= pm.getObjectById(Users.class, this.userlistId);
assertNotNull(ul);
assertNotNull(ul.getUsers().get(0));
assertTrue(ul.getUsers().get(0).getId().equals(this.userId));
pm.close();
}
}

Resources