Tuesday, November 9, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Why in the object retrieved by a JPA findAll() method I cannot access to the field mapped as relationship?

Posted: 09 Nov 2021 08:12 AM PST

I am working on a Spring Boot project using Spring Data JPA and I have the following problem trying to retrieve data.

I have this User class mapping a portal_user DB table:

@Entity  @Table(name = "portal_user")  @Getter  @Setter  public class User implements Serializable {             private static final long serialVersionUID = 5062673109048808267L;            @Id      @Column(name = "id")      @GeneratedValue(strategy=GenerationType.IDENTITY)      private int id;            @Column(name = "first_name")      private String firstName;            @Column(name = "middle_name")      private String middleName;            @Column(name = "surname")      private String surname;            @Column(name = "sex")      private char sex;            @Column(name = "birthdate")      private Date birthdate;            @Column(name = "tex_code")      private String taxCode;            @Column(name = "e_mail")      private String eMail;            @Column(name = "contact_number")      private String contactNumber;            @Temporal(TemporalType.DATE)      @Column(name = "created_at")      private Date createdAt;            @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)      @JsonManagedReference      private Set<Address> addressesList = new HashSet<>();            //@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)      //@JsonManagedReference      //private Set<User_UserType> userToUserTypeAssociation = new HashSet<>();            @ManyToMany(cascade = { CascadeType.MERGE })      @JoinTable(          name = "portal_user_user_type",           joinColumns = { @JoinColumn(name = "portal_user_id_fk") },           inverseJoinColumns = { @JoinColumn(name = "user_type_id_fk") }      )      Set<UserType> userTypes;              public User() {          super();          // TODO Auto-generated constructor stub      }          public User(String firstName, String middleName, String surname, char sex, Date birthdate, String taxCode,              String eMail, String contactNumber, Date createdAt) {          super();          this.firstName = firstName;          this.middleName = middleName;          this.surname = surname;          this.sex = sex;          this.birthdate = birthdate;          this.taxCode = taxCode;          this.eMail = eMail;          this.contactNumber = contactNumber;          this.createdAt = createdAt;      }    }  

As you can see into this entity class there are some relationship, for example this @OnetoMany relationship:

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)  @JsonManagedReference  private Set<Address> addressesList = new HashSet<>();  

This is my Address entity class mapping the address table on my DB:

@Entity  @Table(name = "address")  @Getter  @Setter  @NoArgsConstructor  @AllArgsConstructor   public class Address implements Serializable {             private static final long serialVersionUID = 6956974379644960088L;            @Id      @Column(name = "id")      @GeneratedValue(strategy=GenerationType.IDENTITY)      private int id;            @Column(name = "country")      private String country;            @Column(name = "province")      private String province;            @Column(name = "zip_code")      private String zipCode;            @Column(name = "street")      private String street;            @Column(name = "notes")      private String notes;            //@Column(name = "fk_user_id")      //private int fkUserId;            @ManyToOne      @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error      @JoinColumn(name = "fk_user_id", referencedColumnName = "id")      @JsonBackReference      private User user;        public Address(String country, String province, String zipCode, String street, String notes, User user) {          super();          this.country = country;          this.province = province;          this.zipCode = zipCode;          this.street = street;          this.notes = notes;          this.user = user;      }      }  

I created this unit test method to test the retrieve of all the records into my portal_user table (and the information caming from the relationship):

@Test  @Order(2)  public void RetrieveAllUsers() {            List<User> usersList = this.userRepository.findAll();      System.out.println(usersList.get(0).getAddressesList());      System.out.println(usersList.get(0).getUserTypes());      assertTrue(true);        }  

The findAll() method seems works and the list is retrieved but using the debugger I cannot see the value of the two field representing a relationship, this is what I am ontaining in the "expression" tab of the debugger.

usersList   (id=180)          [0] User  (id=193)            addressesList   PersistentSet  (id=199)               Error   Exception occurred: com.sun.jdi.InvocationException: Exception occurred in target VM occurred invoking method..           birthdate   Timestamp  (id=204)           contactNumber   329123456" (id=208)           createdAt   Date  (id=213)            eMail   xxx@gmail.com" (id=215)           firstName   Luca" (id=216)            id  25            middleName  null              sex M             surname Verdi" (id=217)           taxCode XXX" (id=218)             userTypes   PersistentSet  (id=220)               Error   Exception occurred: com.sun.jdi.InvocationException: Exception occurred in target VM occurred invoking method..       [1] User  (id=196)        [2] User  (id=197)    Add new expression        

As you can see, the value of the addressesList and of the userTypes fields representing my relationship is something like:

Error   Exception occurred: com.sun.jdi.InvocationException: Exception occurred in target VM occurred invoking method..   

As you can see in the previous unit test method code I then tried to access it by:

usersList.get(0).getAddressesList())  

but when this code is performed I obtains this exception:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.easydefi.users.entity.User.addressesList, could not initialize proxy - no Session      at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:606)      at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)      at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)      at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)      at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:327)      at java.base/java.lang.String.valueOf(String.java:3365)      at java.base/java.io.PrintStream.println(PrintStream.java:1047)      at com.easydefi.users.tests.RepositoryTests.UserRepositoryTest.RetrieveAllUsers(UserRepositoryTest.java:86)      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)      at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)      at java.base/java.lang.reflect.Method.invoke(Method.java:567)      at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)      at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)      at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)      at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)      at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)      at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)      at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)      at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)      at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)      at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)      at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)      at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)      at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)      at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)      at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)      at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)      at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)  

What is the problem? What am I missing? How can i try to fix this issue?

Handling errors when inputting dates in python

Posted: 09 Nov 2021 08:11 AM PST

I have a Python script that is asking the user for input of today's date. The method I am using is giving me an error which I'm finding confusing for me to figure out the error. What I'm trying to do is ask the user to input today's date and then output a message if the date is not in the format "mm/dd/yyyy". Any advice on the code and error would be helpful.

from datetime import date  todays_date = input("Enter today's date: ")  try:      todays_date = date.strftime(todays_date, "%m/%d/%Y")  except ValueError:      print("Error: must be in mm/dd/yyyy ")      input = input("press 1 to try again or 0 to exit: ")      if input == "0":          sys.exit()  print("Today's date is {todays_date}")  

Error

todays_date = date.strftime(todays_date, "%m/%d/%Y")  TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object  

mouseover on span to make visible using javascript

Posted: 09 Nov 2021 08:11 AM PST

I'm working on a website that has a large panel. This panel created by an span in the code with class name="_nb8H _BdWj" on it so when i moves my mouse over it the menu will be showing. I need JavaScript code to Keep this span open Just like when my mouseover it then i can Simulator click to one that options.

when the span will be visible i had this this class name inside executed codes but when i leave my mouse it disappears

document.getElementsByClassName("_nb8H _BdWj")[0].click();  

I read some code about "event dispatch" but I did not understand.

AutoMapper How to map one class to another class in a ForMember method

Posted: 09 Nov 2021 08:11 AM PST

So I have got this class structure for my project:

public class SomeType {      public int Id {get; set;}      public List<Customer> Customers {get; set;}  }    public class Customer {       public int Id {get; set;}       public string FirstName {get; set;}  }    public class CustomerDto {      public int Id {get; set;}      public string FirstName {get; set;}  }    public class SomeTypeDto {      public int Id {get; set;}      public List<object> SomeValues {get; set;}  }  

At some point in my project I call it like this:

var result = _mapper.Map<SomeTypeDto>(someType);  

Is there a way to convert the list of type Customer to a list of type CustomerDto upon mapping the SomeType class to SomeTypeDto with AutoMapper? I remember there was a way before with the static Mapper.Map<>() method called inside a MapFrom method when creating the types mapping but it doesn't seem to work with the newer versions.

Why is the text truncating when I export a paginated report to pdf?

Posted: 09 Nov 2021 08:11 AM PST

I have been working on a paginated report via report builder/power bi. When previewing the report in report builder, everything looks fine. When I export to word format, everything looks fine. When I export to PDF, any text that exceeds one line in the report gets truncated.

Sample images of the report are seen here: https://community.powerbi.com/t5/Developer/Paginated-Reports-gt-Text-Truncates-when-using-quot-Export-to/m-p/2178696#M32800

I want to mention that the "can grow" property was mentioned in other threads and it is turned on and works everywhere other than in PDF exporting from what I can see, so I am hoping someone else has seen this issue?

What will be the condition when something has to lie between two lines

Posted: 09 Nov 2021 08:11 AM PST

I have a condition like-

10:50 <= x:y <= 11:20  

Here x:y represents line number and column number respectively, it could be something else like-

10:20 <= x:y <= 10:50  

You get the point, x:y has to lie between two lines, I am getting stuck to figuring out the boolean condition, maybe I could get some help.

How I can draw any function without intervals in python

Posted: 09 Nov 2021 08:11 AM PST

I am trying to create a program to draw functions(equation) like y = x3 but I want to draw the functions without given interval without range, linspace, or else, what I want to make draw the function when I give you, for example, I want to draw this function f(x) = 5*x5-5x**2+6x-2 .

to understand what I mean see this website: https://www.desmos.com/calculator now just when run the program draws the function.

this snippet code from a website but with linspace:

# Import libraries  import matplotlib.pyplot as plt  import numpy as np    # Creating vectors X and Y  x = np.linspace(-2, 2, 100)  y = x ** 2    fig = plt.figure(figsize=(10, 5))  # Create the plot  plt.plot(x, y)    # Show the plot  plt.show()  

if any solution to that with any library like plotly, matplotlib, or another library tell me and I will appreciate that, thank you.

Concatenate two columns from one table and look for where it does not show up in another table mysql

Posted: 09 Nov 2021 08:11 AM PST

I want to concatenate two columns from table1 and check if they are not in table2. table1 has column fname and name, I want to concatenate all fname and lname and check look for the ones that are not in table2 name column. I am able to check if fname alone does not show in another table2, I am also able to concatenate fname and lname as qname columns in table 1, but when I concatenate as qname and check if qname is not in table two then I get an error Error in query (1054): Unknown column 'qname' in 'IN/ALL/ANY subquery'

Here is my query

SELECT CONCAT(table1.fname, " ", table1.lname) AS qname from table1   WHERE qname NOT IN      (SELECT table2.name        FROM table2);  

C++ BucketList class initalization

Posted: 09 Nov 2021 08:11 AM PST

I have been given an assignment related to Linked List Data Structure. I'm having trouble getting started. I just need help initializing the constructor.

BucketList.h

#ifndef BUCKETLIST_H_  #define BUCKETLIST_H_    #include <string>  using std::string;    class Node {      // Data members. Do not change them      string s_; // string stored in this node      Node* next_; // pointer to next node in the list        // even constructors are private!      // so only BucketList can access them      Node();      ~Node();        // You can add other member functions if you want    friend class BucketList; // allow BucketList to access private members  };    class BucketList {    public:      // Constructor. Constructs an empty BucketList with initial capacity      // INITIAL_CAP with no contents.      BucketList();        // Destructor. Deallocate all memory used.      ~BucketList();        // Copy constructor.      BucketList(const BucketList& other);        // Copy assignment operator.      BucketList& operator=(const BucketList& other);        // Return true if the string s is in the BucketList, false otherwise.      bool contains(const string& s) const;        // Insert the string s into the BucketList.      // If s is already in the BucketList, do not change anything.      // If the bucket is going to contain more than one string      // (i.e. the list has more than one node), they should be ordered      // alphabetically (i.e. based on how C++ compares strings)      // If the load factor is going to be exceeded after the insertion      // (i.e. number of strings / capacity of container > MAX_LOAD_FACTOR),      // double the capacity of the container first before the insertion.      // See the assignment webpage for details on doubling.      void insert(const string& s);        // Remove the string s from the BucketList.      // If s is not in the BucketList, do not change anything.      void remove(const string& s);        // Return a string representation of the BucketList, as described      // in the assignment webpage.      // Note that it does not actually print anything to the screen.      // To pass the test cases you must make sure that even the      // white spaces are correct. In particular,      // there should be no space character after the number if no string is in       // that bucket; no space character after the last string of a bucket;      // and no newline character after the last line.      string toString() const;        // The mash function that converts the string s to an integer.      // This really shouldn't be public, but it is for the purpose of      // testing.      int h(const string& s) const;        // Return the number of strings currently stored in the BucketList.      int getSize() const;        // Return the capacity (i.e. size of the array, or number of buckets)      // of the BucketList.      int getCap() const;        // we didn't explain what static and constexpr are, but you can just      // use them like normal constants in BucketList.cpp      static constexpr int INITIAL_CAP = 10; // initial capacity      static constexpr double MAX_LOAD_FACTOR = 0.7; // maximum load factor    private:        Node** buckets_; // pointer to an array of Node*        // You can add any other private member variables or functions      // if you want    };    

No comments:

Post a Comment