Search field is missing in JHipster - jhipster

I generated the JHipster application frontend and backend separately.
jhipster --skip-client
jhipster --skip-server --db=sql --auth=jwt
Imported jdl file to frontend and backend.
jhipster import-jdl 21poindt.jh --skip-client
jhipster import-jdl 21points.jh --skip-server
Backend and frontend run with no error.
CRUD functionalities of generated entities work fine, BUT THE SEARCH FIELD IS MISSING.
When I generated JHipster with the same jdl file, and backend and frontend together, the search field appears as it is expected.
What I did wrong? How can I enable the search field in separate JHispter frontend?
entity Points {
date LocalDate required,
exercise Integer,
meals Integer,
alcohol Integer,
notes String maxlength(140)
}
entity Weight {
timestamp ZonedDateTime required,
weight Double required
}
entity BloodPressure {
timestamp ZonedDateTime required,
systolic Integer required,
diastolic Integer required
}
entity Preferences {
weeklyGoal Integer required min(10) max(21),
weightUnits Units required
}
enum Units {
KG, LB
}
relationship OneToOne {
Preferences{user(login)} to User
}
relationship ManyToOne {
BloodPressure{user(login)} to User,
Weight{user(login)} to User,
Points{user(login)} to User
}
// Set pagination options
paginate BloodPressure, Weight with infinite-scroll
paginate Points with pagination
// Use Data Transfert Objects (DTO)
dto * with mapstruct
// Set service options to all except few
service all with serviceImpl
filter Points

#JonRuddell When I generated JHipster frontend with --skip-server I was not asked about the elasticsearch. After your comment, I have added "searchEngine": "elasticsearch" to .yo-rc.json and regenerated app. Now it shows the search field. Thanks

Related

migrate int id to uuid string using prisma

I want to my database column int id to string uuid format.
id Int #id #default(autoincrement())
// to
id String #id #default(uuid())
Rewriting prisma code Above, migration works but, the id just was stringified sequence like '1' or '2', and I want to reset id to uuid. But I didn't find this uuid function which algorithm derived from and architecture(where it derived from database, rust, or client?). What the best way to reassign id? I can generate uuid from node clients?
[In Addition]
I found explanation in referred to document
This is derived from prisma.
You can still use uuid() when using introspection by manually
changing your Prisma schema and generating Prisma Client,
in that case the values will be generated by Prisma's query engine.
but can we call it from client api?
I found prisma using uuid v4 as default, so any library or programming language is available as manner of how it generates.
I post discussion thread in prisma repository, too.

Seeder method for Azure Database in EF Core 2

What is the proper method to seed data into an Azure Database? Currently in development I have a seeder method that inserts the first couple of users as well as products. The Users (including admin user) username and password are hardcoded into the Seed method, is this an acceptable practice?
As far as the products are concerned, I have a json file with the product names and descriptions - which in development the seeder method iterates through and inserts the data.
To answer your question "The Users (including admin user) username and password are hardcoded into the Seed method, is this an acceptable practice?"
No you should keep your password in cleartext format, though you can keep it it encrypet mode and seed it.
In EF Core 2.1, the seeding workflow is quite different. There is now Fluent API logic to define the seed data in OnModelCreating. Then, when you create a migration, the seeding is transformed into migration commands to perform inserts, and is eventually transformed into SQL that that particular migration executes. Further migrations will know to insert more data, or even perform updates and deletes, depending on what changes you make in the OnModelCreating method.
Suppose thethree classes in my model are Magazine, Article and Author. A magazine can have one or more articles and an article can have one author. There’s also a PublicationsContext that uses SQLite as its data provider and has some basic SQL logging set up.
Let take an example of single entity type.
Let’s start by seeing what it looks like to provide seed data for a magazine—at its simplest.
The key to the new seeding feature is the HasData Fluent API method, which you can apply to an Entity in the OnModelCreating method.
Here’s the structure of the Magazine type:
public class Magazine
{
public int MagazineId { get; set; }
public string Name { get; set; }
public string Publisher { get; set; }
public List<Article> Articles { get; set; }
}
It has a key property, MagazineId, two strings and a list of Article types. Now let’s seed it with data for a single magazine:
protected override void OnModelCreating (ModelBuilder modelBuilder)
{
modelBuilder.Entity<Magazine> ().HasData
(new Magazine { MagazineId = 1, Name = "MSDN Magazine" });
}
A couple things to pay attention to here: First, I’m explicitly setting the key property, MagazineId. Second, I’m not supplying the Publisher string.
Next, I’ll add a migration, my first for this model. I happen to be using Visual Studio Code for this project, which is a .NET Core app, so I’m using the CLI migrations command, “dotnet ef migrations add init.” The resulting migration file contains all of the usual CreateTable and other relevant logic, followed by code to insert the new data, specifying the table name, columns and values:
migrationBuilder.InsertData(
table: "Magazines",
columns: new[] { "MagazineId", "Name", "Publisher" },
values: new object[] { 1, "MSDN Magazine", null });
Inserting the primary key value stands out to me here—especially after I’ve checked how the MagazineId column was defined further up in the migration file. It’s a column that should auto-increment, so you may not expect that value to be explicitly inserted:
MagazineId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true)
Let’s continue to see how this works out. Using the migrations script command, “dotnet ef migrations script,” to show what will be sent to the database, I can see that the primary key value will still be inserted into the key column:
INSERT INTO "Magazines" ("MagazineId", "Name", "Publisher")
VALUES (1, 'MSDN Magazine', NULL);
That’s because I’m targeting SQLite. SQLite will insert a key value if it’s provided, overriding the auto-increment. But what about with a SQL Server database, which definitely won’t do that on the fly?
I switched the context to use the SQL Server provider to investigate and saw that the SQL generated by the SQL Server provider includes logic to temporarily set IDENTITY_INSERT ON. That way, the supplied value will be inserted into the primary key column. Mystery solved!
You can use HasData to insert multiple rows at a time, though keep in mind that HasData is specific to a single entity. You can’t combine inserts to multiple tables with HasData. Here, I’m inserting two magazines at once:
modelBuilder.Entity<Magazine>()
.HasData(new Magazine{MagazineId=2, Name="New Yorker"},
new Magazine{MagazineId=3, Name="Scientific American"}
);
For a complete example , you can browse through this sample repo
Hope it helps.

Add plot to sample jhipster app

A very basic question from a newbie to the wonderful jhipster ecosystem.
How do I add an additional page to my app that displays two plots based on queries on the database?
I have created the demo jhipster app that tracks authors and books in a postgres database as described in the tutorial.
I would now like to add a summary page to my sample jhipster app that displays two plots based on data retrieved from an sql query.
1) barplot of total books published per author
select author_id, count(*)
from book
group by author_id
2) line plot showing number of publications for each author per year
select author_id,extract(year from publication_date) as year,count(*)
from book
group by author_id,year
I would normally use R/Shiny and plotly to create this type of dashboard, but would really appreciate any guidance on how to achieve the same using the jhipster framework
Thanks
Iain
I see 2 tasks here. In general you first prepare 2 API endpoints to deliver the data to your frontend (keep in mind, JHI provides both server and client), and then using plotly (js) to do your plots
preparing API
you should translate your SQL query to JPA, like this:
public interface BookRepository extends JpaRepository<Book,Long> {
#Query("select b.authorId, count(b.id) from Book b group by b.authorId ")
List<Book> findAllGroupByAuthor();
#Query("select b.authorId, YEAR(b.publicationDate) as year,count(*) from Book b group by b.authorId, b.year")
List<Book> findAllGroupByAuthorAndYear();
}
then you add this to some RestControllers. Here is an example
#RestController
#RequestMapping("/api/books/query/")
public class CustomBookQueryResource {
private BookRepository bookRepository;
public CustomBookQueryResource(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
#GetMapping("/group_by_author")
public ResponseEntity<List<Book>> groupByAuthor() {
return ResponseEntity.ok(bookRepository.findAllGroupByAuthor());
}
#GetMapping("/group_by_author_and_year")
public ResponseEntity<List<Book>> groupByAuthorAndYear() {
return ResponseEntity.ok(bookRepository.findAllGroupByAuthorAndYear());
}
}
so until this point, you should already have some api endpoints, serving your data. Now you should add your custom query book service in angular
angular
.module('<yourApp>')
.factory('CustomBookQuery', CustomBookQuery);
CustomBookQuery.$inject = ['$http'];
function CustomBookQuery ($http) {
var resourceUrl = 'api/books/query/';
return {
findAllGroupByAuthor: function () {
return $http.get(resourceUrl + 'group_by_author');
},
findAllGroupByAuthorAndYear: function () {
return $http.get(resourceUrl + 'group_by_author_and_year');
}
};
}
Now you just can inject your service and pass its promises resolves to your plotly, which is already has and JS part and a Angular implementation
(I coded above code from mind, so it's not tested)
For simple cases where your query only involves one entity it might be as simple as adding a method or methods to the associated Repository interface and have Spring Data handle the query generation.
Take a look at https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation
and if you'd prefer to supply the query
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
You could then add an HTML page with JS to render the plot of the results of the query.
For situations that require a join over entities there’s a few possible approaches…
You could create a view in PostGresQL that would effectively make a table which is this query and then create an Entity for it (and then render them in your fav JS lib). This is my preferred option. You would need to update the liquidbase file to create the view. You would make an Entity and you would create a Spring Data repository interface (which will result in the autogeneration of a REST service etc) and then render using HTML and JS.
Alternatively, JPA entities can be queries using JPQL. That will give you a collection of objects that you can render with Angular.js or whatever your fav JS library.
http://www.oracle.com/technetwork/articles/vasiliev-jpql-087123.html
You can also use JPA to map native SQL to a PoJo (see especially the JPA 2.1 notes) and then create a REST service and render using your JS.
JPA : How to convert a native query result set to POJO class collection
http://www.thoughts-on-java.org/jpa-native-queries/

Best way to manage internationalization in database

I ' ve some troubles , managing my i18n in my database
For now I ' just two languages available on my application , but in order to be scalable, I would like to do it the "best" way.
I could have duplicated all fields like description_fr, description_en but I was no confortable with this at all. What I've done for now, is a external table , call it content, and its architecture is like this :
id_ref => entity referenced id (2)
type => table name (university)
field => field of the specific table (description)
lang => which lang (fr, en, es…)
content => and finally the appropriate content.
I think it can be important to precise, I use sequelizeJS as ORM. So I can use a usefull hooks as afterFind, afterCreate and afterUpdate. So Each time I wanna to find a resource for example, after find it, my hook retrieve all content for this resource and set definitly my object with goods values. It works, but I'm not in love with this.
But I have some troubles with this :
It's increase considerably my number of requests to the database : If I select 50 rows for example, I have to do 50 requests more.. , and just for a particular model. If I have nested models, it's exponential…
Then, It's complicated to fetch data by content i18ned. Example find a university with a specific name is complicated.
And It's a lot of work for updating etc...
So I wonder, if it would be a good idea , to save as a JSON, directly in the table concerned , the data. Something like
{
fr : { 'name':'Ma super université' },
en : { 'name':'My kick ass university' }
}
And keep on using Sequelize Hooks to build and insert proper data into my object.
What do you think ?
How do you manage this ?
EDIT
I use a mysql database
It concerns around 20 fields (cross models)
I have to set the default value using a my default_lang if there is no content set (e.g, event.description in french will be the same as the english one, if there is no content set)
I used this npm package sequelize-i18n. It worked pretty fine for me using sequelize 3.23.2, unfortunately it seems does not have support for sequelize 4.x yet.

Loading related entities when dealing with Models and Collections from Backbone to Express / Mongoose

I have a UserService object that is essentially a Service with additional configuration parameters and is attached to a User. In my View I would like to render a list of these UserServices however the model is formed as such:
UserService = Backbone.Model.extend({
defaults: {
id: 0,
user_id: 0, // This needs to reference the user object somehow
service_id: 0, // This needs to reference the service object somehow
length: 216000,
price: 1000
}
});
If I bind this model to the view, what is rendered ends up being the service_id instead of the parameter I need to render: service.name.
My questions are:
What should be stored in the UserService model at service? The full service object? Mongoose ID? Some other ID? (Please specify a suggestion)
Where should I get the information for this service.name / When should I pull the Service object to get that information? It would be nice to be able to do service.name in the view when rendering...
Is there a function to chain--upon loading the model, load related models that are needed?
Overall I just need an understanding of how related models work in Backbone / Express / Mongoose.
Any help is appreciated!
Update: After doing a bit of reading I have a couple different methods I can see:
Within the constructor / initializer load the Service object into the UserService object based on the reference ID returned from the server.
My questions with that one then become... what is the reference ID? Where do I put the newly retrieved object into, possibly in place of the ID?
Use the toJSON method to return an asthetic version of the UserService where it retreives the Service object and would return an object with the service name in it's place:
{
id: ???,
service_name: "this was retrieved from the service object in the toJSON method",
length: "1 hour", // converted from within the toJSON method
price: 10.00 // converted from cents to dollars in the toJSON method
}
Or maybe a combination? Thoughts?
Parse models handle loading related entities well, there is also library called Backbone Relational that can help with this.
Otherwise, my best recommendation is to store the object's ID and fetch the related entity upon success of fetching the first entity.
Anyone needing a code example just comment here and I'll see what I can come up with.

Resources