JPA Entity for Drop Down columns(How to populate the dropdown) - dropdown

I'm in the same boat where this guy was 6 years ago
my question is did i do anything wrong here?
<select name="gender">
<c:forEach items="${Person.Gender.values()}" var="type">
<option value="${type}">${type}</option>
</c:forEach>
</select>
I have a POJO named Account
#Entity
public class Account implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private long AccountNumber;
private String fName;
private String lName;
…
And I have a enum
public enum Gender {male, female};
#Enumerated(EnumType.STRING)
private Gender gender;
}
This is the way I’m triying to populate the dropped down list in the jsp, but it is not working
<select name="gender">
<c:forEach items=“${Account.Gender.values()}" var="type">
<option value="${type}">${type}</option>
</c:forEach>
</select>
i have tried to use jsp usebean tag to import the class and I’m still not get expected result. instead i GETjavax.el.PropertyNotFoundException:`

To solve the problem i (1) - created a getGenderType() and (2)-add use tag for Account class in the jsp.
#Entity
public class Account implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private long AccountNumber;
private String fName;
private String lName;
…
And I have a enum
public enum Gender {male, female};
#Enumerated(EnumType.STRING)
private Gender gender;
}
//this will available in the jsp as genderTypes
public List <Gender> getGenderTypes(){
return Arrays.asList( Gender.male,
Gender.female);
}
this is the jsp
<jsp:usebean id="account" scope="session" class="java.class.Account"/>
<select name="gender">
<c:forEach items=“${account.genderTypes}" var="type">
<option value="${type}">${type}</option>
</c:forEach>
</select>

Related

How to create Entity class with composite kays (Kotlin, Spring boot)

I have a database diagram, which i need to implement in Entity classes
Diagram image
User entity:
#Entity
class User (
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val idUser: Int = -1,
#Column(unique=true)
val name: String = "",
#Column(unique=true)
val email: String = "",
#Column(nullable = false)
val password: String = ""
)
Post entity:
User entity:
#Entity
data class Post (
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val idPost: Int = -1,
#Column(nullable = false)
val title: String = "",
#Column(nullable = false)
val body: String = "",
#Column(nullable = false)
val date: String = Date().toString()
)
I just don't understand how to organize a relationship between tables.
Also IDEA reports an error when a table does not have Primary Key.
Help me with implementation of UserPost Entity class.
SOLVE
Okay, I have a solution, just add a data source (I used MySQL) and use Generate Kotlin Entities.kts then IDEA will automatically create all Entity classes. I think it is the most easy way.
You can define your entities as below with required details such as #columns on attributes and other details.
The below classes are just for reference and to guide on the path.
Please read more about Composite keys and refer the link https://www.baeldung.com/jpa-composite-primary-keys
#Entity
#IdClass(UserPost.class)
public class Post {
#Id
private int idPost;
#Id
private int idUser;
private String title;
private String body;
private LocalDateTime date;
}
#Entity
#IdClass(UserPost.class)
class User{
#Id
private int idPost;
#Id
private int idUser;
private String name;
private String email;
private String password;
}
class UserPost implements Serializable {
private static final long serialVersionUID = 1L;
private int idPost;
private int idUser;
//No-Args constructor and All-Args constructor
//hashcode
//equals
}
Its in java, In kotlin there will not be much diffrence. There is another way to implement the composite key using #Embeddable and #EmbeddableID

Design optaplanner constraints of booking system

I would like to design a booking system using optaplanner, bellow my business model:
Customers (id, name) //Customer table
Services(id, name, description, duration) //services that a customer can book, duration can be 15min, 30min, ..., N x 15min
Employees(id, name) //Employee tables
Appointment(id, customerId, employeeId, serviceId, startTime, endTime)
To book an appointment, the customer will select:
The day of the appointment (mandatory)
A list of services (mandatory)
A list of employees (optional)
I would like to know I can design the model to return the list of availability for a given day, given list of services.
Bellow a basic pseudo-code model :
#Entity
public class Service extends PanacheEntityBase {
#Id
#GeneratedValue
#NotNull
private Long id;
#NotBlank
private String name;
private int durationInGrains;
}
public class TimeGrain {
public static final int GRAIN_LENGTH_IN_MINUTES = 15;
private int grainIndex; // unique
private int startingMinuteOfDay;
}
#Entity
public class Employee extends PanacheEntityBase {
#PlanningId
#Id
#GeneratedValue
#NotNull
private Long id;
#NotBlank
private String name;
}
#Entity
public class Appointment extends PanacheEntityBase {
#Id
#GeneratedValue
#NotNull
private Long id;
private Employee employee;
private Service service;
private LocalDateTime startTime;
private LocalDateTime endTime;
}
#PlanningEntity
public class Availability {
#PlanningVariable(valueRangeProviderRefs = { "timeGrainRange" })
private TimeGrain startingTimeGrain;
#PlanningVariable(valueRangeProviderRefs = "providerRange")
private Provider provider;
private Service service;
}
#PlanningSolution
public class AppointmentAvailability {
#ValueRangeProvider(id = "timeGrainRange")
#ProblemFactCollectionProperty
private List<TimeGrain> timeGrainList;
#ProblemFactCollectionProperty
#ValueRangeProvider(id = "providerRange")
private List<Provider> providerList;
#ProblemFactCollectionProperty
#ValueRangeProvider(id = "appointmentsRange")
private List<Appointment> appointmentList;
#PlanningEntityCollectionProperty
private List<Availability> availabilityList;
#PlanningScore
private HardMediumSoftScore score;
}
As I am new to optaplanner, could you please advise if this is the way to go?
UPDATE 1: I have simplified the problem to the minimum for design purposes.
Take a look at the meeting scheduling example in optaplanner-examples, to get inspired on how to model it. Also see the Time Grain pattern in the docs in the section Design Patterns. The school timetabling quickstart follows the Timeslot pattern instead.

Hibernate LazyLoading initialization of List

I've typical User and Comment-Models. One user has more comments.
On one usecase i want to get only a user from db, without comments.
I thought, as soon i tell "getComments()", so only in this moment, my List will initialized with
something like "select comment from Comment c where c.userId = 1" from Hibernate.
But my List of comments will be initialized everytime when i say findyById or "select user from User".
#Entity
#Getter #Setter
#ToString(exclude = {"comments")
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class User implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Builder.Default
#OneToMany(mappedBy="user", fetch = FetchType.LAZY)
private List<Comment> comments = new ArrayList<>();
}
My Comment Model:
#Entity
#Getter #Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Comment implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Builder.Default
#ManyToOne(fetch = FetchType.LAZY)
private User user; }
UserRepository:
public interface UserRepository extends JpaRepository<User, Long> {
#Query("SELECT user FROM User user WHERE user.id =:id")
Optional<User> findUserById(#Param("id") long id); }
When i tell:
userRepository.findUserById(1);
So i see at first only one select-statment for user.
Few seconds later i see next statment for comment, but i did not tell "user.getComments()"
So how can i get User-Model without any Lazy-List's with related Object?

Entry and Serialisation

My project is in the form:
Class Persistant :
#Entity
public class Produit implements Serializable {
private static final long serialVersionUID = -3352484919001942398L;
#Id
#GeneratedValue
private Long id;
private String module;
private String produit;
//getter&&setter
Class Dao
public List<Entry<Integer, List<Produit>>> parProduit(String cat) {
.......
HashMap<Integer, List<Produit>> legaux = new HashMap<Integer, List<Produit>>();
........
List<Map.Entry<Integer, List<Produit>>> entries = new ArrayList<Entry<Integer, List<Produit>>>(legaux.entrySet());
return entries;
}
when i execute this code i get this error :
java.io.NotSerializableException: java.util.HashMap$Node
java.util.HashMap.EntrySet<K, V>
is not serializable.
legaux.entrySet()
probably returns set of type java.util.HashMap.EntrySet, you may want to check that.

How to show value of a navigation property with Entity Framework and MVC?

I have the following query and am trying to show the Category name(s) in the index view. I can verify in LinqPad that the category is getting filled for each post.
I have tried #item.PostCategory which shows System.Collections.Generic.HashSet1[be_Categories] while #item.PostCategory.FirstOrDefault.CategoryName throws Object reference not set to an instance of an object. And I can verify that each post has the correct number of categories associated with it via #item.PostCategory.Count.
How exactly do i show the value of be_Categories for each post in the index view?
Public Function SelectAll() As IQueryable(Of PostSummaryDTO)
Implements IPostRepository.SelectAll
db = New BetterBlogContext
Dim posts As IQueryable(Of PostSummaryDTO) = db.be_Posts.OrderByDescending
(Function(x)x.DateCreated).Include(Function(c)
c.be_Categories).Select(Function(s) New PostSummaryDTO With {.PostId = s.PostRowID,
.PostDateCreated = s.DateCreated, .PostText = s.PostContent, .PostGuid = s.PostID,
.PostSummary = s.Description, .PostCategory = s.be_Categories, .PostTitle = s.Title,
.PostIsPublished = s.IsPublished, .PostTag = s.be_PostTag})
Return posts
Entity:
Partial Public Class be_Posts
<Key>
Public Property PostRowID As Integer
Public Property BlogID As Guid
Public Property PostID As Guid
<StringLength(255)>
Public Property Title As String
Public Property Description As String
<AllowHtml> Public Property PostContent As String
Public Property DateCreated As Date?
Public Property DateModified As Date?
<StringLength(50)>
Public Property Author As String
Public Property IsPublished As Boolean?
Public Property IsCommentEnabled As Boolean?
Public Property Raters As Integer?
Public Property Rating As Single?
<StringLength(255)>
Public Property Slug As String
Public Property IsDeleted As Boolean
Public Overridable Property be_PostTag As ICollection(Of be_PostTag)
<ForeignKey("be_Categories")> Public Overridable Property be_Categories As ICollection(Of be_Categories)
Public Property be_PostCategory As ICollection(Of be_PostCategory)
End Class
Ok this seems to work - needed a second for each loop in the index view:
#For Each x In item.PostCategory
#x.CategoryName
Next
The whole code:
<div class="row">
#For Each item In Model
#<div class="col-xs-6 col-sm-6 col-lg-6 col-md-6">
<div class="panel panel-default panel-body content">
<b>#item.PostDateCreated.ToShortDateString <span class="pull-right">#item.PostDateCreated.AddHours(3).ToShortTimeString</span></b>
#For Each x In item.PostCategory
#x.CategoryName
Next
<div class="galleryImgWrapper">
<a href="#Url.Action("Details", "Posts", New With {.id = item.Id, .title = BetterBlog.Core.Helpers.SeoHelper.ToSeoUrl(item.PostTitle)}, Nothing)">
#Html.Raw(item.PostSummary.GetImage)
</a>
</div>
<h4>#Html.ActionLink(item.PostTitle, "Details", "Posts",
New With {.id = item.Id, .title = ToSeoUrl(item.PostTitle)}, Nothing)</h4>
#Html.Raw(item.PostSummary.RemoveImgWithRegex)
</div>
</div>
#<div class="clear"></div>
Next
</div>