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
Related
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 want to store a List of class : RestApiResponse into MySql. But getting below error:
org.hibernate.HibernateException: Could not determine a type for class: com.try.sreapi.beans.RestApiResponse
Below are my classes:
Entity class : SREAPITestingHistory.java
#NamedQueries(#NamedQuery(name="getSREAPITestHistory.findAll", query="SELECT a FROM SREAPITestingHistory a"))
#SqlResultSetMapping(name="sreapitestinghistoryres",
entities=#EntityResult(entityClass=SREAPITestingHistory.class))
#Entity
#Table(name="sreapi_testing_history_details")
#Transactional
public class SREAPITestingHistory implements Serializable{
private static final long serialVersionUID = -7221709766109001257L;
#Id
#Column(name="request_time")
private String request_time;
#Column(name="req_id")
private String req_id;
#Column(name="app_name")
private String app_name;
#Column(name="request_name")
private String request_name;
#Lob
#Column(name="response_body")
private List<RestApiResponse> response;
public String getRequest_time() {
return request_time;
}
public void setRequest_time(String request_time) {
this.request_time = request_time;
}
public String getReq_id() {
return req_id;
}
public void setReq_id(String req_id) {
this.req_id = req_id;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getRequest_name() {
return request_name;
}
public void setRequest_name(String request_name) {
this.request_name = request_name;
}
public List<RestApiResponse> getResponse() {
return response;
}
public void setResponse(List<RestApiResponse> response) {
this.response = response;
}
}
Repository Class: SREAPITestingRepository.java
#Repository
public interface SREAPITestingRepository extends CrudRepository< SREAPITestingHistory, String> {
#Modifying
#Transactional
#Query(value="INSERT into sreapi_testing_history_details (request_time,req_id,app_name,request_name,response_body)"+ "VALUES (:request_time,:req_id,:app_name,:request_name,:response_body)", nativeQuery = true)
public void setApiTestHistoryDetails(#Param("request_time") String request_time,#Param("req_id") String req_id,#Param("app_name") String app_name,#Param("request_name") String request_name,#Param("response_body") List<RestApiResponse> response_body);
}
When I am trying to add values for response_body which is actually a List of RestApiResponse class and I am getting Could not determine a type for class: com.try.sreapi.beans.RestApiResponse exception
From Official doc
A Lob may be either a binary or character type.
The Lob type is inferred from the type of the persistent field or
property, and except for string and character-based types defaults to
Blob.
Example 1:
#Lob #Basic(fetch=LAZY) #Column(name="REPORT")
String report;
Example 2:
#Lob #Basic(fetch=LAZY) #Column(name="EMP_PIC",
columnDefinition="BLOB NOT NULL") protected byte[] pic;
So you can convert your list of data into json string or bytes to store.
Ok so I am new to spring and don't really know how this works. I have been trying a few things and think its close to doing it but not getting any data from the server and giving me this error
Unsatisfied dependency expressed through constructor argument with index 4 of type [jp.co.fusionsystems.dimare.crm.service.impl.MyDataDefaultService]: : Error creating bean with name 'MyDataDefaultService' defined in file
My end point
//mobile data endpoint
#RequestMapping(
value = API_PREFIX + ENDPOINT_MyData + "/getMyData",
method = RequestMethod.GET)
public MyData getMyData() {
return MyDataDefaultService.getData();
}
My Object
public class MyData {
public MyData(final Builder builder) {
videoLink = builder.videoLink;
}
private String videoLink;
public String getVideoLink()
{
return videoLink;
}
public static class Builder
{
private String videoLink = "";
public Builder setVideo(String videoLink)
{
this.videoLink = videoLink;
return this;
}
public MyData build()
{
return new MyData(this);
}
}
#Override
public boolean equals(final Object other) {
return ObjectUtils.equals(this, other);
}
#Override
public int hashCode() {
return ObjectUtils.hashCode(this);
}
#Override
public String toString() {
return ObjectUtils.toString(this);
}
}
The Repository
public classMyServerMyDataRepository implements MyDataRepository{
private finalMyServerMyDataJpaRepository jpaRepository;
private final MyDataConverter MyDataConverter = new MyDataConverter();
#Autowired
publicMyServerMyDataRepository(finalMyServerMyDataJpaRepository jpaRepository) {
this.jpaRepository = Validate.notNull(jpaRepository);
}
#Override
public MyData getData() {
MyDataEntity entity = jpaRepository.findOne((long) 0);
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
The DefaultService that gets called by the endpoint
public class MyDataDefaultService {
private static final Logger logger = LoggerFactory.getLogger(NotificationDefaultService.class);
private finalMyServerMyDataRepository repository;
#Autowired
public MyDataDefaultService(MyServerMyDataRepository repository) {
this.repository = Validate.notNull(repository);
}
//Get the data from the server
public MobileData getData()
{
logger.info("Get Mobile Data from the server");
//Get the data from the repository
MobileData mobileData = repository.getData();
return mobileData;
}
}
The Converter
public class MyDataConverter extends AbstractConverter<MyDataEntity, MyData>
{
#Override
public MyData convert(MyDataEntity entity) {
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
}
My Entity
#Entity
#Table(name = “myServer”)
public class MyDataEntity extends AbstractEntity{
#Column(name = "video_link", nullable = true)
private String videoLink;
public String getVideoLink() {
return videoLink;
}
public void setVideoLink(final String videoLink) {
this.videoLink = videoLink;
}
}
Thank you for any help with this
Hibernate entity should have default constructor defined and implement Serializable interface as well, assume AbstractEntity matches the requirement. Hibernate won't accept an entity without a primary key so you have to define the one too:
#Entity
#Table(name = “myServer”)
public class MyDataEntity implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "video_link", nullable = true)
private String videoLink;
public MyDataEntity() {
}
...setters&getters
}
MyData object represents the JSON server response, you can use Jackson annotations to control the result JSON properties:
public class MyDataResponse {
#JsonProperty("video_link")
private String videoLink;
public MyDataResponse() {
}
public MyDataResponse(String videoLink) {
this.videoLink = videoLink;
}
...setters&getters
}
Spring has an awesome project so called Spring Data that provides the JPA repositories, so there's no even the #Repository annotation ever needed:
public class MyDataRepository extends CrudRepository<MyDataEntity, Long> {
}
The Builder class represents the Service layer:
#Service
public class MyDataService {
#Autowired
private MyDataRepository myDataRepository;
public MyDataResponse getMyData(Long id) {
MyDataEntity entity = myDataRepository.findOne(id);
...rest logic, copy necessary data to MyDataResponse
}
}
Then a controller is:
#RestController // #ResponseBody not needed when using like this
public MyDataController {
#Autowired
private MyDataService myDataService;
#RequestMapping("/getMyData") // no need to specify method for GET
public MyDataResponse getMyData(#RequestParam("ID") Long myDataId) {
... validation logic
return myDataService.getMyData(myDataId); // return response
}
}
Now it should work, don't forget to add required dependencies to your classpath.
Input paramter to my webservice method is an Object of Class AddSingleDocRequest. This class contains all the input fields as class instance variable with their getter and setter. I want to make some of the input fields mandatory. What is the best way to achieve this ?
Following is the code snippet:
**//webservice method
public String uploadDoc(AddSingleDocRequest request)
{
}
**//Request Class**
public class AddSingleDocRequest
{
private String sFilepath;
private String sDataClass;
public void setDataClassName(String dataClassName)
{
this.sDataClass= dataClassName;
}
public String getDataClassName() {
return sDataClass;
}
public void setFilePath(String filePath)
{
this.sFilepath=filePath;
}
public String getFilePath()
{
return sFilepath;
}
}
I want to make sFilePath parameter as mandatory.
Add the next JAX-B annotations:
#XmlType(name = "AddSingleDocRequestType", propOrder = {
"sFilepath", "sDataClass"
})
public class AddSingleDocRequest {
#XmlElement(name = "sFilepath", required = true)
private String sFilepath;
#XmlElement(name = "sDataClass", required = false)
private String sDataClass;
public void setDataClassName(String dataClassName) {
this.sDataClass = dataClassName;
}
public String getDataClassName() {
return sDataClass;
}
public void setFilePath(String filePath) {
this.sFilepath = filePath;
}
public String getFilePath() {
return sFilepath;
}
}
See more in Using JAXB to customize mapping for JAX-WS web services.
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.