Hi all I've a small problem to map one-to-one using JPA 2 persistence with EclipseLink vendor and maybe any of you will be able to help.
I want to map one table with another but the field in second table is optional. So I've created #Entity for the first table:
Amp class
private AmpApInfo ampApInfo;
private String apid;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public String getApid() {
return this.apid;
}
public void setApid(String apid) {
this.apid = apid;
}
#OneToOne
#JoinColumn(name="apid")
public AmpApInfo getAmpApInfo() {
return this.ampApInfo;
}
public void setAmpApInfo(AmpApInfo ampApInfo) {
this.ampApInfo = ampApInfo;
}
and #Entity for the second table
AmpApInfo class
private String apid;
private Amp amp;
private String prodOrderNo;
public AmpApInfo() {
}
#OneToOne(optional=true, mappedBy="ampApInfo")
public Amp getAmp() {
return this.amp;
}
public void setAmp(Amp amp) {
this.amp = amp;
}
#Id
public String getApid() {
return apid;
}
public void setApid(String apid) {
this.apid = apid;
}
#Column(name="prod_order_no")
public String getProdOrderNo() {
return this.prodOrderNo;
}
public void setProdOrderNo(String prodOrderNo) {
this.prodOrderNo = prodOrderNo;
}
Now when I want to find prodOrderNo like
public Amp selectProdInfo(String name) {
// TODO Auto-generated method stub
Amp amp = Transactions.getEntityManager().find(Amp.class, name.trim());
System.out.println("order number" + amp.getAmpApInfo().getProdOrderNo());
return amp;
}
I'm expecting to get null cos its not there but I'm getting java.lang.NullPointerException on the line
System.out.println("order number" + amp.getAmpApInfo().getProdOrderNo());
Any one can help???
Either amp is null or amp.getAmpApInfo() is returning null, and you are trying to call methods on them.
Related
I'm trying to do an application using Spring Boot MVC and I've run into a problem. For the Post and Put methods I receive status 200 ok but the values are "null". The new registration on database is created but just the Id (autoincrement) column is populated and received in Postman response. Could someone help me please?
` #RequestMapping("/api")
#RestController
public class ExtractedNumbersController {
private final ExtractedNumbersService extractedNumbersService;
#Autowired
public ExtractedNumbersController(ExtractedNumbersService extractedNumbersService) {
this.extractedNumbersService = extractedNumbersService;
}
#PostMapping("/addExtractedNumbers")
public ExtractedNumbers addExtractedNumbers(#RequestBody ExtractedNumbers extractedNumbers) {
return extractedNumbersService.addExtractedNumbers(extractedNumbers);
}
#GetMapping("/findAllExtractedNumbers")
public List<ExtractedNumbers> findAllActivities() {
return extractedNumbersService.findAllExtractedNumbers();
}
#GetMapping("findExtractedNumbersById/{id}")
public Optional<ExtractedNumbers> findExtractedNumbersById(#PathVariable("id") Integer id) {
return extractedNumbersService.findByIdExtractedNumbers(id);
}
#PutMapping("/updateExtractedNumbers/{id}")
public ExtractedNumbers updateProduct(#PathVariable("id") Integer id, #RequestBody ExtractedNumbers extractedNumbers) {
Optional<ExtractedNumbers> extractedNumbersFromDatabase = extractedNumbersService.findByIdExtractedNumbers(id);
if (extractedNumbersFromDatabase.isPresent()) {
extractedNumbersFromDatabase.get().setExtractedNumbers(extractedNumbers.getExtractedNumbers());
extractedNumbersFromDatabase.get().setExtractionDate(extractedNumbers.getExtractionDate());
final ExtractedNumbers updatedExtractedNumbers = extractedNumbersService.addExtractedNumbers(extractedNumbersFromDatabase.get());
return updatedExtractedNumbers;
}
return extractedNumbersService.addExtractedNumbers(extractedNumbers);
}
#DeleteMapping("/deleteExtractedNumbersById/{id}")
public void deleteExtractedNumbersById(#PathVariable("id") Integer id) {
extractedNumbersService.deleteExtractedNumbers(id);
}
}
#Data
#Table
#Entity
#AllArgsConstructor
#NoArgsConstructor
public class ExtractedNumbers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer extractedNumbersId;
#Column
private String extractedNumbers;
#Column
private String extractionDate;
public ExtractedNumbers(String extractedNumbers, String extractionDate) {
this.extractedNumbers = extractedNumbers;
this.extractionDate = extractionDate;
}
public String getExtractedNumbers() {
return extractedNumbers;
}
public void setExtractedNumbers(String extractedNumbers) {
this.extractedNumbers = extractedNumbers;
}
public String getExtractionDate() {
return extractionDate;
}
public void setExtractionDate(String extractionDate) {
this.extractionDate = extractionDate;
}
}
public interface ExtractedNumbersService {
List<ExtractedNumbers> findAllExtractedNumbers();
ExtractedNumbers addExtractedNumbers(ExtractedNumbers extractedNumbers);
Optional<ExtractedNumbers> findByIdExtractedNumbers(Integer extractedNumbersId);
ExtractedNumbers update(ExtractedNumbers extractedNumbers);
void deleteExtractedNumbers(Integer extractedNumbersId);
}
#Service
public class ExtractedNumbersServiceImpl implements ExtractedNumbersService {
private final ExtractedNumbersRepository extractedNumbersRepository;
public ExtractedNumbersServiceImpl(ExtractedNumbersRepository extractedNumbersRepository) {
this.extractedNumbersRepository = extractedNumbersRepository;
}
#Override
public List<ExtractedNumbers> findAllExtractedNumbers() { return extractedNumbersRepository.findAll() ; }
#Override
public ExtractedNumbers addExtractedNumbers(ExtractedNumbers extractedNumbers) {
return extractedNumbersRepository.save(extractedNumbers);
}
#Override
public Optional<ExtractedNumbers> findByIdExtractedNumbers(Integer extractedNumbersId) {
return extractedNumbersRepository.findById(extractedNumbersId);
}
#Override
public ExtractedNumbers update(ExtractedNumbers extractedNumbers) {
return extractedNumbersRepository.save(extractedNumbers);
}
#Override
public void deleteExtractedNumbers(Integer extractedNumbersId) {
extractedNumbersRepository.deleteById(extractedNumbersId);
}
}`
[Database][1]
Postman
Extracted Numbers Class
Are your attributes in ExtractedNumbers consistent with the database table column?
if your table column is like extracted_numbers you need to do the underline to camel
This is my first time making a discord bot that attached to a DB using spring boot and Gradle. I followed some tutorials and the discord bot is working properly but when I want to call my DB it returns null in my Java. I tried to use the same query in my PHPmyadmin to see if it is really a null but in reality, it should have returned a value.
This is my Main class
#SpringBootApplication
public class Main {
private static Logger logger = LogManager.getLogger(Main.class);
/**
* The entrance point of our program.
*
* #param args The arguments for the program. The first element should be the bot's token.
*/
public static void main(String[] args) {
// if (args.length < 1) {
// System.err.println("Please provide a valid token as the first argument!");
// return;
// }
SpringApplication.run(Main.class, args);
// Enable debugging, if no slf4j logger was found
FallbackLoggerConfiguration.setDebug(true);
// The token is the first argument of the program
String token = "Nzg3NTI4MTU0MDM3MjIzNDU2.X9WQvw.Ix9zeiZB5KWwGkxfUAU0pjy4xF0";
// We login blocking, just because it is simpler and doesn't matter here
DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();
// Print the invite url of the bot
logger.info("You can invite me by using the following url: " + api.createBotInvite());
// Add listeners
api.addMessageCreateListener(new CommandManager("!")); // <-- I want to run this command
// Log a message, if the bot joined or left a server
api.addServerJoinListener(event -> logger.info("Joined server " + event.getServer().getName()));
api.addServerLeaveListener(event -> logger.info("Left server " + event.getServer().getName()));
}
}
From there, it should lead me to my CommandManager.java within my Command directory
public class CommandManager implements MessageCreateListener {
String prefix="!";
DieCommand dieCommand = new DieCommand();
EightBallCommand eightBallCommand = new EightBallCommand();
UserInfoCommand userInfoCommand = new UserInfoCommand();
NijiMemberCommand nijiMemberCommand = new NijiMemberCommand();
CurrencyConverterCommand currencyConverterCommand = new CurrencyConverterCommand();
public CommandManager(String pfx) {
this.prefix = pfx;
}
#Override
public void onMessageCreate(MessageCreateEvent event) throws NullPointerException {
String[] command = event.getMessageContent().split(" ");
if(command[0].contains(prefix+"roll")){
dieCommand.onMessageCreate(event);
return;
}
if(command[0].contains(prefix+"8ball")){
eightBallCommand.onMessageCreate(event);
return;
}
if(command[0].contains(prefix+"userinfo")){
userInfoCommand.onMessageCreate(event);
return;
}
if(command[0].contains(prefix+"whois")){
nijiMemberCommand.onMessageCreate(event);
return;
}
if(command[0].contains(prefix+"convert")){
currencyConverterCommand.onMessageCreate(event);
return;
}
}
}
For this class, I have a configurationManager for it
#Configuration
public class ConfigurationManager {
#Bean
public CommandManager commandManager() {
return new CommandManager("!");
}
}
The command that I want to test is !whois noraneko which will lead me to NijiMemberCommand.java
#Component
public class NijiMemberCommand implements MessageCreateListener {
#Autowired
MemberListService memberListService;
private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(Main.class);
#Override
public void onMessageCreate(MessageCreateEvent event){
String[] command = event.getMessageContent().split(" ");
if (command.length == 1) {
logger.info("Will it enter here? no?");
event.getChannel().sendMessage("You are missing argument, the command is consist of !member <name of liver>");
return;
}
event.getChannel().sendMessage(memberListService.visual(command[1]));
logger.info("Please enter here..... " + command[1] + " " + memberListService.visual(command[1]));
event.getChannel().sendMessage(memberListService.visual(command[1]));
return;
}
}
Until this point, there is nothing wrong until it reached to event.getChannel().sendMessage(memberListService.visual(command[1])); which in my mind it should lead me to my Service layer which is this
#Service
public class MemberListServiceImpl implements MemberListService {
#Autowired
MemberListDB memberListDB;
private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(Main.class);
public String capitalize(String name){
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
#Override
#Transactional
public String visual(String nama) {
logger.info("Masuk "+ nama);
String[] name = nama.split(" ");
String result =null;
for(String e : name){
result+=capitalize(e)+" ";
}
return memberListDB.showVisual(result);
}
}
and this is my DB
#Repository
#EnableJpaRepositories
public interface MemberListDB extends JpaRepository<MemberListModel, Long> {
#Query(value = "select m.visual FROM member_list as m, nickname AS n WHERE n.nick_id = m.nick AND n.nickname=:w", nativeQuery = true)
String showVisual(#Param("w") String nama);
}
I tried to run a similar query within my PHPmyadmin, it shows non-null value
Where did I go wrong?
// Edit
This is my model that I use for my program
package com.nijicord.nijiworld.db.Model;
import com.nijicord.nijiworld.db.Repository.MemberListDB;
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.io.Serializable;
/**
* This is the table model that will hold the majority of member's info
*/
#Entity
#Table(name = "member_list")
public class MemberListModel implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "nick")
private Long nick_id;
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "social_media")
private Long social_id;
#NotNull
#Column(name = "name")
private String name;
#NotNull
#Column(name = "branch")
private String branch;
#NotNull
#Column(name = "debut_3d")
private boolean debut;
#Column(name = "illustrator")
private String illustrator;
#NotNull
#Column(name = "visual")
private String visual;
public Long getNick_id() {
return nick_id;
}
public void setNick_id(Long nick_id) {
this.nick_id = nick_id;
}
public Long getSocial_id() {
return social_id;
}
public void setSocial_id(Long social_id) {
this.social_id = social_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public boolean isDebut() {
return debut;
}
public void setDebut(boolean debut) {
this.debut = debut;
}
public String getIllustrator() {
return illustrator;
}
public void setIllustrator(String illustrator) {
this.illustrator = illustrator;
}
public String getVisual() {
return visual;
}
public void setVisual(String visual) {
this.visual = visual;
}
}
////Edit
This is the error
2020-12-20 15:37:54.405 ERROR 11840 --- [utorService - 1] o.j.core.util.event.EventDispatcherBase : Unhandled exception in a listener thread for FFJ THREAD EMPORIUM!
java.lang.NullPointerException: null
at com.nijicord.nijiworld.command.NijiMemberCommand.onMessageCreate(NijiMemberCommand.java:27) ~[main/:na]
at com.nijicord.nijiworld.command.CommandManager.onMessageCreate(CommandManager.java:44) ~[main/:an]
//////Edit
I have edited my original post with the flow and the code.
You are using nama.toUpperCase() here.
#Override
#Transactional
public String visual(String nama) {
logger.info("Masuk "+ nama);
return memberListDB.showVisual(nama.toUpperCase());
}
But in query you are using nickname in lowercase e.g. noraneko. I think this might be a problem. You are using uppercase instead of lowercase.
I have simple Java Class that is getting stored to MongoDB through Spring JPA -
public class PlanRecoveryStrategy {
String planId;
String processId;
String strategyId;
public String getPlanId() {
return planId;
}
public void setPlanId(String planId) {
this.planId = planId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getStrategyId() {
return strategyId;
}
public void setStrategyId(String strategyId) {
this.strategyId = strategyId;
}
}
This is my DataAccessObject Class -
#Repository("PlanRecoveryStrategy")
public interface PlanRecoveryStrategyDao extends MongoRepository<PlanRecoveryStrategy, String> {
#Query(value = "{ 'planId' : ?0, 'processId' : ?1, 'strategyId' : ?2}", delete = true)
List<PlanRecoveryStrategy> deletePlanRecoveryStrategy(String planId, String processId, String strategyId);
}
However, on trying to delete, I get the error saying - No id property found for object of type class com.apeiron.dataModel.plan.PlanRecoveryStrategy
What is the reason for the error?
Just create a field with #Id annotation and create getters and setters for it
I am new to Spring Data JPA and Hibernate. By looking at different examples I built a working model for CRUD operations on one entity, I am having trouble in joining two tables to extract AF_NAME using AF_ID from another table which is Foreign key. A null column is created with the names of and while accessing, null is returned.please check if I am following preocedure for joins and point me to any tutorial know.
I followed this solution and still there is no progress.
#Entity
#Configuration
#EnableAutoConfiguration
#Table(name = "AFF_CONFIG")
public class AFF_CONFIG implements Serializable {
#Id
#Column(name = "AFF_CONFIG_ID")
private String AFF_CONFIG_ID;
#Column(name = "AFF_ID")
private String AFF_ID;
#Column(name = "CH_ID")
private String CH_ID;
#Column(name = "M_ID")
private Long M_ID;
#Column(name = "KEY")
private String KEY;
#Column(name = "VALUE")
private String VALUE;
#Column(name = "SYSTEM")
private String SYSTEM;
private AFF aff;
#LazyCollection(LazyCollectionOption.TRUE)
#ManyToOne
#JoinColumn(name = "AFF_ID")
public AFF getAff() {
return aff;
}
public void setAffiliate(AFF aff) {
this.aff = aff;
}
public String getAFF_CONFIG_ID() {
return AFF_CONFIG_ID;
}
public void setAFF_CONFIG_ID(String aFF_CONFIG_ID) {
AFF_CONFIG_ID = aFF_CONFIG_ID;
}
public String getAFF_ID() {
return AFF_ID;
}
public void setAFF_ID(String aFF_ID) {
AFF_ID = AFF_ID;
}
public String getCH_ID() {
return CH_ID;
}
public void setCHANNEL_ID(String cH_ID) {
CH_ID = cH_ID;
}
public Long getM_ID() {
return M_ID;
}
public void setM_ID(Long m_ID) {
M_ID = m_ID;
}
public String getKEY() {
return KEY;
}
public void setKEY(String kEY) {
KEY = kEY;
}
public String getVALUE() {
return VALUE;
}
public void setVALUE(String vALUE) {
VALUE = vALUE;
}
public String getSYSTEM() {
return SYSTEM;
}
public void setSYSTEM(String sYSTEM) {
SYSTEM = sYSTEM;
}
Second entity is:
#Entity
#Table(name = "AFF")
public class AFF implements Serializable {
#Column(name = "AFF_NAME")
private String AFF_NAME;
#Column(name = "AFF_CODE")
private String AFF_CODE;
#Id
#Column(name = "AFF_ID")
private String AFF_ID;
private Set<AFF_CONFIG> someAff = new HashSet<AFF_CONFIG>();
#LazyCollection(LazyCollectionOption.TRUE)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "aff")
public Set<AFF_CONFIG> getSomeAff() {
return someAff;
}
public void setSomeAff(Set<AFF_CONFIG> someAff) {
this.someAff = someAff;
}
public String getAFF_ID() {
return AFF_ID;
}
public void setAFF_ID(String aFF_ID) {
AFF_ID = aFF_ID;
}
public String getAFF_NAME() {
return AFF_NAME;
}
public void setAFF_NAME(String aFF_NAME) {
AFF_NAME = aFF_NAME;
}
public String getAFF_CODE() {
return AFF_CODE;
}
public void setAFF_CODE(String aFF_CODE) {
AFF_CODE = aFF_CODE;
}
Since this is many to one relation I created set type in one and object type in another as defined in other places.Created a repository by extending crud and added a query. Excise the bunch of different annotations, I included them in hoping to solve the null entry.
#Repository
public interface MarketRepository extends CrudRepository<AFF_CONFIG,String> {
Page<AFF_CONFIG> findAll(Pageable pageable);
#Query("Select a,b from AFF_CONFIG a, AFF b where a.AFF_ID = b.AFF_ID" )
public List<AFF_CONFIG> getAffData();
}
the applicatoin is working fine even after some tinkering until I Included these annotations. Now there is this error:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: aff.
I solved the issue with the help of my Supervisor. Looks like we have to follow naming specifications for Class and variables. And one more correction is to remove collection type object and change it to just object (removed set in aff class).I will post the corrected later, to compare and contrast.
I have configured the OneToMany mappings for my tables.So when inserting values to the fisrt table on second time it gives me an error Cannot insert duplicate key row in object. Here is my tables.
Table -1 (feature_id is pk and auto generated by table) and name is inserting by me.
Feature_id(PK)
Name
feature table has index
"GO
CREATE UNIQUE INDEX idx_Name ON "dbo"."Feature"(Name)
Table-2 (Feature_Version_id PK and auto generated by table)
Feature_Version_id ,
Version_Name
Feature_id
POJO classes are :
#Entity
#Table(name="FEATURE")
public class Feature {
private int feature_id;
private String name;
private Set<FeatureVersion> featureversion = new HashSet<FeatureVersion>(0);
public Feature() {
}
public Feature(String name ,Set<FeatureVersion> featureversion) {
this.name = name;
this.featureversion = featureversion;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="FEATURE_ID")
public int getFeature_id() {
return feature_id;
}
public void setFeature_id(int feature_id) {
this.feature_id = feature_id;
}
#Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch=FetchType.LAZY,mappedBy="feature")
public Set<FeatureVersion> getFeatureversion() {
return featureversion;
}
public void setFeatureversion(Set<FeatureVersion> featureversion) {
this.featureversion = featureversion;
}
}
Second table POJO class:
#Entity
#Table(name="FEATURE_VERSION")
public class FeatureVersion {
private int feature_version_id;
private String version_name;
private int feature_id;
private Feature feature;
private Set<PartFeatureVersion> partfeatureversion = new HashSet<PartFeatureVersion>(0);
public FeatureVersion() {
}
public FeatureVersion(Feature feature, String version_name, int feature_id) {
this.feature = feature;
this.version_name = version_name;
this.feature_id = feature_id;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="FEATURE_VERSION_ID")
public int getFeature_version_id() {
return feature_version_id;
}
public void setFeature_version_id(int feature_version_id) {
this.feature_version_id = feature_version_id;
}
#Column(name="VERSION_NAME")
public String getVersion_name() {
return version_name;
}
public void setVersion_name(String version_name) {
this.version_name = version_name;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="feature_id")
public Feature getFeature() {
return feature;
}
public void setFeature(Feature feature) {
this.feature = feature;
}
#OneToMany(fetch=FetchType.LAZY,mappedBy="featureversion")
public Set<PartFeatureVersion> getPartfeatureversion() {
return partfeatureversion;
}
public void setPartfeatureversion(Set<PartFeatureVersion> partfeatureversion) {
this.partfeatureversion = partfeatureversion;
}
}
Main class :
Session session = (Session) HibernateUtil.getSessionFactory().openSession();
Feature feature = new Feature();
FeatureVersion featurever = new FeatureVersion();
feature.setName("stack");
session.save(feature);
featurever.setVersion_name("12.2");
featurever.setFeature(feature);
feature.getFeatureversion().add(featurever);
session.save(featurever);
session.getTransaction().commit();
session.flush();
Here is my input values :
(feature id generated by table)
First attempt for first table: stack
First attempt for second table : 12.2
(feature_id come from feature table)
second attempt for first table: stack
second attempt for second table : 12.3
OneToMany configuration will take care if more than one values come to OneToMany releationship ? Or i need to check if value is exist then just the version name ? These all values loop through from the list. Please advise what should i do here .
Thanks,