want to autowire DAO class in my entity class - spring

i have a method which i need to call in my entity class company.java.
but when i run my application it throws null pointer exception didn't fount that DAO object in entity class..
How can i get that object in entity class please help
This is my entity class..
package com.salebuild.model;
/**
* Define a company.
*
* #author mseritan
*/
#Entity
#Table(name = "company", uniqueConstraints = {#UniqueConstraint(columnNames = "name")})
#XmlRootElement
#XmlSeeAlso(value = ArrayList.class)
public class Company implements PublishableIF, Serializable, PersistableIF, HistoryIF, AddressableIF {
private static final Logger log = LoggerFactory.getLogger( Company.class );
#Autowired
private CompanyDAO companyDAO;
// CONSTANTS -----------------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
// ATTRIBUTES ----------------------------------------------------------------------------------
private Long id;
#NotBlank
private String name;
private String formerName;
private CorporateTitle topLevelExec;
private List<CompanySite> sites;
private List<CompanyAlias> aliases;
#NotNull
private Industry industry;
private Company parentCompany;
private String emailTopology;
#NotNull
private Double revenue;
#NotNull
private Long numberEmployees;
private CustomerType.Type customerType;
private Boolean recruiter = false;
private int publishState;
private CompanyStatus status;
private Boolean excludeCompany = false;
private CompanyType companyType;
private String salesifyCompanyId;
private CompanySiteType companySiteType;
private String websiteUrl;
private String sourceVendor;
private String notes;
private List<CompanySpecializedRanking> specializedList = new ArrayList<CompanySpecializedRanking>();
#NotNull
private NAICSCode naicsCode;
#NotNull
private SICCode sicCode;
private Long version;
private List<Technology> technologies = new ArrayList<Technology>();
private List<CompanyContact> contacts;
private String phoneNumber;
private String faxNumber;
private String email;
private User userCreated;
private Date dateCreated;
private User userLastModified;
private Date dateLastModified;
private User userLastResearcher;
private Date dateLastResearcher;
#NotBlank
private String street1;
private String street2;
private String street3;
private String city;
private String zipCode;
private State state;
private Country country;
private String specRankingListName;
private Integer specRankingRank;
private Integer specRankingYear;
private String modifiedCompanyName;
private String formattedRevenue;
private String formattedEmployeeSize;
private List<JobPostingRaw> unconfirmedTechnologies;
// ACESSORS ------------------------------------------------------------------------------------
//getter setter for other fields //
this.specRankingYear = specRankingYear;
}
/**
* #param modifiedCompanyName
*
*/
#Column(name="modifiedCompanyName")
public String getModifiedCompanyName() {
return modifiedCompanyName;
}
public void setModifiedCompanyName(String modifiedCompanyName) {
if(modifiedCompanyName==null)
this.modifiedCompanyName=modifiedCompanyName;
else{
this.modifiedCompanyName =companyDAO.updateCompanyName(modifiedCompanyName);
}
}
#Transient
public List<JobPostingRaw> getUnconfirmedTechnologies() {
return unconfirmedTechnologies;
}
public void setUnconfirmedTechnologies(
List<JobPostingRaw> unconfirmedTechnologies) {
this.unconfirmedTechnologies = unconfirmedTechnologies;
}
}
my DAO class is like that --
package com.salebuild.dao;
import com.salebuild.model.Company;
import com.salebuild.model.search.EntitySearchCriteria;
import com.salebuild.model.search.SortedResultsPage;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public interface CompanyDAO extends CrudDAO<Company> {
Company findByNameOrAlias(String name);
List<Company> findBySearchTerm(String searchTerm, Integer start, Integer count);
// SortedResultsPage<Company> findPaged(EntitySearchCriteria criteria);
List<Long> findIds(EntitySearchCriteria criteria);
List<Company> find(Collection<Long> ids);
/**
* For just finding the company name and not looking for alias names.
*
* #param name
* #return
*/
public Company findByName( String name );
public Company findByModifiedName(String name,Company... c);
public int companyCountSinceLastLogin(Long id);
Set<Long> findDistinctIds(EntitySearchCriteria criteria);
public Integer getCompanyCountByRegion(Long regionId,List techCatIds);
List<Company> findAllCompanies(Company instance);
public List<Company> findAllModifiedCompanies(Company instance);
public String updateCompanyName(String name);
}

The easiest option is to implement factory for building entities. Then you can use AutowireCapableBeanFactory to autowire dependencies:
public abstract class GenericFactory<T> {
#Autowired
private AutowireCapableBeanFactory autowireBeanFactory;
public T createBean() {
// creation logic
autowireBeanFactory.autowireBean(createdBean);
return createdBean;
}
}
Of course you can pass object (created or retrieved) and just autowire it.
Another option is to use #Configurable - it automatically injects dependencies. http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-atconfigurable
You can find more details in my post: http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html

JPA entities are meant to be POJOs i.e. simple Java beans which do not have dependencies and have getters and setters which contain no complex logic.
It would be better to create a service which is responsible for saving and updating your entity which is used throughout your code. This service can then be responsible for executing the logic you wish to put in your setter using dependencies which can be autowired.
The issue you have is that you Spring is not responsible for the creation of your entity. You either instantiate it using new or you obtain it from your JPA implementation. Either way there is no opportunity for Spring to autowire declared dependencies.
As an aside it's not good practice to autowire private variables. See this blog post for a fuller discussion.

Related

CQEngine Query nested object using parser.retrieve

I have a nested object like
public class SQSMessage implements Serializable {
private String type;
private boolean isEntity;
private String eventType;
private SystemInfo systemInfo;
private DomainAttributes domainAttributes;
#Data
public static class SystemInfo implements Serializable {
private String identifier;
private String ownedBy;
private Payload payload;
private EntityTags entityTags;
private long createdOn;
private String createdBy;
private long version;
private long lastUpdatedOn;
private String lastUpdatedBy;
private String attrEncKeyName;
#Data
public static class Payload implements Serializable {
private String bucketName;
private String objName;
private String encKeyName;
private byte[] payloadBytes;
private byte[] decryptedBytes;
private byte[] sanitizedBytes;
}
#Data
public static class EntityTags implements Serializable {
private List<Tag> tags;
#Data
public static class Tag implements Serializable {
private String tagName;
private String tagValue;
}
}
}
#Data
public static class DomainAttributes implements Serializable {
private String updatedByAuthId;
private String saveType;
private String docName;
private String ceDataType;
private String year;
private String appId;
private String formSetId;
private String appSku;
private String deviceId;
private String deviceName;
}
}
I would like to query the collection of SQSObjects by applying a filter like
ResultSet<SQSMessage> results = parser.retrieve(indexedSQSMessage, "SELECT * FROM indexedSQSMessage WHERE type='income' and DomainAttributes.saveType in ('endSession', 'cancelled')or (DomainAttributes.countryCode is null or DomainAttributes.countryCode='US'");
Is that possible using CQEngine? if yes.. please send me the examples.
The reason why I want o make that as sql... where clause is dynamic for various use cases.
Your example is more complicated than it needs to be for the question, so I am just skimming it. (Read about SSCCE)
However generally this kind of thing should be possible. See this related question/answer for how to construct nested queries: Can CQEngine query an object inside another object
If you set up attributes like that, you should be able to use them in SQL queries as well as programmatically.

I don't know why the double values are displayed in postman. Is the my code correct?

This is my Book class:
#Entity
#Table(name="book")
public class Book {
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(targetEntity=Category.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JoinColumn(name="CategoryId")
public Category category;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(length=10)
private int book_id;
#Column(length=128)
private String title;
#Column(length=64)
private String author;
#Column(length=200)
private String description;
#Column(length=10)
private int ISBN;
#Column(length=10)
private float price;
private Date published_Date;
#Lob
#Column
#Basic(fetch = FetchType.LAZY)
private byte[] icon;
//getter and setter
}
This is my Category class:
#Entity
#Table(name="category1")
public class Category {
#Id
#Column(length=12)
#GeneratedValue(strategy=GenerationType.AUTO)
public int CategoryId;
#Column(length=50)
public String CategoryName;
//#JsonBackReference
#OneToMany(mappedBy="category")
private List<Book> books = new ArrayList<Book>();
//getter and setter
}
The relationship between them is one to many.
This is my Category Service class
#Service
#Transactional
public class AdminServiceImpl implements AdminService {
#Autowired
private CategoryDao dao;
#Autowired
private BookDao dao1;
#Override
public List<Category> getAllCategory(){
return dao.findAll();
}
}
My Controller class
#RestController
#RequestMapping("/bookstore")
public class CategoryController {
#Autowired
private AdminService service;
#GetMapping("/GetAllCategory")
private ResponseEntity<List<Category>> getAllCategory() {
List<Category> catlist = service.getAllCategory();
return new ResponseEntity<List<Category>>(catlist, new HttpHeaders(), HttpStatus.OK);
}
}
My category table already has data.When i try to display them it is showing double values.
Displaying values using Postman
The Category table in the Database: Database table
Jackson's ObjectMapper uses the Java bean pattern and it expects the following
public class Foo {
public Object bar;
public Object getBar() {...}
public void setBar(Object bar) {...}
}
The getters and setters start with get and set, respectively, followed by the corresponding field name with its first letter capitalized.
Change
CategoryId to categoryId (first letter lowercase)
and
CategoryName to categoryName

JPQL Join and class cast exception

I am using JPA with Hibernate in spring boot.
I have two jpa entities
#Entity
#Table(name="courses_type")
public class CoursesType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="course_id")
private int courseId;
#Column(name="level")
private int level;
private int credential;
private String status;
private String type;
#Column(name="updated_by")
private int updatedBy;
#Column(name="updated_on")
private Timestamp updatedOn;
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="credential", referencedColumnName="value_id",insertable=false,updatable=false)
#Where(clause="status='live'")
private BaseAttributeList credentialData;
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="level", referencedColumnName="value_id",insertable=false,updatable=false)
#Where(clause="status='live'")
private BaseAttributeList courseLevelData;
... setters and getters
}
Second Entity
#Entity
#Table(name="attribute_list")
public class AttributeList implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="value_id")
private int valueId;
private String status;
#Column(name="value_name")
private String valueName;
}
Now I am trying to write a JPQL Query in CourseTypeRepo
#Query("Select sct.courseId, sct.credential, sct.credentialData from CoursesType"
+ " sct where sct.courseId IN(?1) and sct.status = ?2")
List<CoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);
Now when I am iterating the result, I am getting class Cast Exception that
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.domain.CoursesType
Basically what I am trying to fetch the complete data using one jpql query.
How should I fix this?
If don't want to fetch full object but only some its properties you have to provide a projection then use it in your query method, for example:
public interface PartialCoursesType {
Integer getCourseId(),
Integer getCredential(),
BaseAttributeList getCredentialData()
}
#Query("select sct.courseId as courseId, sct.credential as credential, sct.credentialData as credentialData...")
List<PartialCoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);
To make the trick works you have to use aliases in the query...

Neo4j RelationshipEntity StackOverflow

I'm having trouble understanding how the #RelationshipEntity works. I've tried following examples, but even though I think I'm following the same pattern as the example, I end up witha stackoverflow, because the Relationship Entity grabs the NodeEntity, which has the RelationshipEntity, and on and on...
My model is:
(:Vendor)-[:BELONGS_TO {active: true, sinceDate: date}]->(:Store)
So my two nodes are Vendor and Store:
#NodeEntity
#Data
public class Vendor {
#GraphId
private Long id;
private Long vendorId;
private String name;
private String address;
#Relationship(type = "OWNS")
private Collection<Inventory> inventory;
#Relationship(type = "BELONGS_TO")
private Collection<Store> store;
}
#NodeEntity
#Data
public class Store {
#GraphId
private Long id;
private Long storeId;
private String name;
private String address;
private String email;
#Relationship(type = "BELONGS_TO", direction = Relationship.INCOMING)
private List<StoreParticipant> storeParticipant;
}
And my RelationshipEntity:
#RelationshipEntity(type = "BELONGS_TO")
#Data
public class StoreParticipant {
#GraphId
private Long id;
#StartNode
private Vendor vendor;
#EndNode
private Store store;
private int count;
private double price;
private boolean negotiable;
private boolean active;
}
I based this off of the Movie example which had (:Person)-[:ACTED_IN]->(:MOVIE) and the acted_in relationship was ROLE
This is happening when I call the repository method findByVendorId
#Repository
public interface VendorRepository extends GraphRepository<Vendor> {
List<Vendor> findByVendorId(Long vendorId);
}
If you're referencing this from both ends, you need to reference the relationship entity, not the node entity directly.
Store looks fine but Vendor contains
#Relationship(type = "BELONGS_TO")
private Collection<Store> store;
when it should be
#Relationship(type = "BELONGS_TO")
private Collection<StoreParticipant> store;

Nested Mapping in Mapstruct

I am new to MapStruct API, can anyone say how to do nested Mapping.
I have two classes one is my actual purchaseOrder class, which is known my target class, the other is EDPurchaseOrder class which known as source file, here don't worry about the naming conventions I used, just go with source and target files.
Source Classes
Source class EDCustomerOrder and its reference classes
public class EDCustomerOrder{
private Integer orderID;
private String orderNumber;
private BigDecimal orderTotalQty;
private String UOM;
private PickupDTO pickupPoints;
private Integer supplierID;
private String supplierName;
private String supplierNature;
private EDAddress supplierEDAddress;
}
public class EDPickup{
private List<EDPOItem> items;
}
public class EDAddress{
private String addressLine1;
private String addressLine2;
private String addressLine3;
private String city;
private String state;
private string countryCode;
private String country;
private String postalCode;
}
public class EDPOItem{
private Integer itemID;
private String itemCode;
private String itemDescription;
private Integer itemQuantity;
}
Target classes
Here my target class CustomerOrder and its reference classes
public class CustomerOrder{
private Integer orderID;
private String orderNumber;
private List<Pickup> pickupPoints;
private Supplier supplierDetail;
}
public class Pickup{
private Integer pickupID;
private Integer pickupLocationNumber;
private List<POItem> items;
}
public class POItem{
private Integer itemID;
private String itemCode;
private String itemDescription;
private Integer itemQuantity;
}
public class Supplier{
private Integer supplierID;
private String supplierName;
private String supplierNature;
private Address supplierAddress;
}
public class Address{
private String addressLine1;
private String addressLine2;
private String addressLine3;
private String city;
private String state;
private string countryCode;
private String country;
private String postalCode;
}
So I suppose you have the same hierarchy of objects on the target side, e.g. a SongDTO, LibraryDTO and TrackDTO.
Then you'd have to declare a mapping method for each of those pairs of corresponding objects, configuring it via #Mapping as needed:
public interface MyMapper {
#Mapping(source="name", target="title")
SongDTO songToDto(Song song);
LibraryDTO libraryToDto(Library library);
TrackDTO trackToDto(Track track);
}
Then e.g. the generated implementation of songToDto() will invoke libraryToDto() in order to map the song's library into the song DTO's library DTO.
Also check out the reference guide to learn more.
#Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CandidateProfessionalEntityAndDTOMapper {
#Mappings({
#Mapping(source = "company.companyId", target = "companyId"),
})
Clazz1
entityToReferencesMapping(Clazz2 entity);
}
public class Clazz2 {
private String companyName;
private Company company;
}
public class Company{
Integer companyId;
}
public class Clazz1 {
private String companyId;
private String companyName;
}

Resources