Why is my data getting associated with wrong column in mysql db? - mysql

I have two tables connected with a many to many relationship using a composite key:
Table1
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "user_name")
private String userName;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
private String password;
private String authorization;
#OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JsonManagedReference
private List<UserProduct> userProducts = new ArrayList<>();
#OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Orders> orders = new ArrayList<>();
Table2
#Entity
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int price;
private double mass;
private double alcohol;
private String picture;
private int amount;
#OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<UserProduct> userProducts = new ArrayList<>();
#OneToMany(
mappedBy = "orders",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<OrderProduct> orderProducts = new ArrayList<>();
Table with composite key
#Entity
#Table(name = "user_product")
public class UserProduct {
#EmbeddedId
private UserProductId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
#JsonBackReference
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("productId")
private Product product;
#Column(name = "amount_of_new_products")
private int amountOfNewProducts;
When I make a REST call to UserProduct table so i can update the product value using this payload:
{
"user": 4,
"product": 2,
"amountOfNewProducts": 32
}
it writes the information depending on what is the user id and not the product id. For this payload it would write in like this:
{
"id": 3,
"name": "Grimbergen Blanche",
"price": 132,
"mass": 0.33,
"alcohol": 6.0,
"picture": "https://i.imgur.com/qIq1OrC.png",
"amount": 502,
"userProducts": [],
"orderProducts": []
},
{
"id": 4,
"name": "Grimbergen Blonde",
"price": 132,
"mass": 0.33,
"alcohol": 6.7,
"picture": "https://i.imgur.com/OnioHd5.png",
"amount": 435,
"userProducts": [
{
"id": {
"productId": 2,
"userId": 4
},
"product": {
"id": 2,
"name": "Lav Premium",
"price": 73,
"mass": 0.33,
"alcohol": 4.9,
"picture": "https://i.imgur.com/T3gCAOE.png",
"amount": 1862,
"userProducts": [],
"orderProducts": []
},
"amountOfNewProducts": 32
}
],
"orderProducts": []
},
So basically even though i passed in 2 as product id the information will be written in product with id 4 just because the users id is 4. Any kind of a clue where I might me messing up would be appreciated.

You need to fix mappedBy = "user" in Product entity. It must be "product", like this:
#OneToMany(
mappedBy = "product",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<UserProduct> userProducts = new ArrayList<>();
Also check that you have correct #JoinColumn in UserProductId (ufortunately, you didn't put code for it to the question).

Related

Spring JPA Projection duplicates parent entity when fetching nested collection with JPQL

Quick explanation
While fetching a nested collection from a JPQL query it serializes one parent object for each nested object. The intended behavior would be serializing one single parent object with a single collection/set of objects.
Using Spring DATA/DATA REST
JPQ Query
#Query(
"""
select distinct ticketOrder.id as id, user.name as name, ticket as tickets from TicketOrder ticketOrder
inner join User user on user.id = ticketOrder.user.id
inner join Ticket ticket on ticket.ticketOrder.id = ticketOrder.id
where user.uid = :uid
"""
)
fun findByUserUid(uid: UUID, pageable: Pageable): Page<TicketOrderProjection>
Related Entity Classes
TicketOrder
class TicketOrder(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "order_id", nullable = false)
val id: Long? = null,
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(nullable = false)
val user: User,
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(nullable = false, updatable = false)
val raffle: Raffle? = null,
#OneToMany(mappedBy = "ticketOrder", cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.LAZY)
var tickets: MutableList<Ticket> = mutableListOf(),
#OneToOne(fetch = FetchType.LAZY)
var transaction: Transaction?,
#CreationTimestamp
#Column(name = "created_at", updatable = false)
val createdAt: Timestamp? = null,
#UpdateTimestamp
#Column(name = "updated_at")
val updatedAt: Timestamp? = null,
#Column(name = "completed_at", nullable = true)
var completedAt: LocalDateTime? = null,
#Column
var checkoutCode: String? = null,
#Enumerated(EnumType.STRING)
#Column(name = "order_status", nullable = false)
var status: TicketOrderStatus
)
/* ... omitted for brevity */
Ticket
#Entity
class Ticket(
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ticket_id", nullable = false)
val id: Long? = null,
#Column(name = "ticket_number", nullable = false, columnDefinition = "UNIQUE")
val ticketNumber: Int,
#ManyToOne
#JoinColumn
var ticketOrder: TicketOrder? = null,
#ManyToOne
#JoinColumn
var raffle: Raffle
)
User
class User(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id", nullable = false)
val id: Long? = null,
#Column(nullable = false)
val name: String,
#Column(nullable = false)
val phone: Long,
#Column(nullable = false)
val email: String,
#Column(nullable = false, updatable = false)
val uid: UUID = UUID.randomUUID(),
#CreationTimestamp
#Column(name = "created_at", updatable = false)
val createdAt: Timestamp? = null
)
Projections
TicketOrderProjection
#Projection(types = [TicketOrder::class])
interface TicketOrderProjection {
val id: Long
val name: String
val tickets: Set<TicketsProjection>
}
TicketsProjection
#Projection(types = [Ticket::class])
interface TicketsProjection {
#get:Value("#{target.id}")
val id: Int
}
Finally
Response at RestController
{
"content": [
{
"name": "Raphael Heizer",
"id": 10,
"tickets": [
{
"id": 21
}
]
},
{
"name": "Raphael Heizer",
"id": 10,
"tickets": [
{
"id": 22
}
]
},
{
"name": "Raphael Heizer",
"id": 10,
"tickets": [
{
"id": 23
}
]
}
],
"pageable": {
// omitted
}
Expected response
{
"content": [
{
"name": "Raphael Heizer",
"id": 10,
"tickets": [
{
"id": 21,
},
{
"id": 22
},
{
"id": 23
}
]
},
],
"pageable": {
// omitted
}

.Net 3.1 DataSeeding order of operation problem

I'm trying to seed a database with about 1000 users and agents and about 5000 posts.
I have added the users and agents but when I try to add the posts the migration gets created normally but the update-database command return an error.
I tried adding a user manually, created a post with the users id and added a migration just for the post and it worked.
I think that this is a order of operations problem. I'm thinking that when the post is being inserted to the database it cannot find the user it is looking for because the user is not in the database yet.
Any help is greatly appreciated.
Thank you for your time in advance <3.
The error reads:
Build started...
Build succeeded.
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (25ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id', N'Baths', N'Beds', N'BuildingType', N'CategoryId', N'City', N'County', N'CreatedAt', N'Description', N'HouseNumber', N'IsActive', N'IsDeleted', N'IsPrioritize', N'IsPublished', N'Latitude', N'Longitute', N'OwnerId', N'PostalCode', N'Price', N'Size', N'State', N'Street', N'StreetNumber', N'Title') AND [object_id] = OBJECT_ID(N'[Post]'))
SET IDENTITY_INSERT [Post] ON;
INSERT INTO [Post] ([Id], [Baths], [Beds], [BuildingType], [CategoryId], [City], [County], [CreatedAt], [Description], [HouseNumber], [IsActive], [IsDeleted], [IsPrioritize], [IsPublished], [Latitude], [Longitute], [OwnerId], [PostalCode], [Price], [Size], [State], [Street], [StreetNumber], [Title])
VALUES (1, 3, 5, 1, 1, N'New York', N'New Work', '2022-08-04T10:58:44.5986172+02:00', N'We are selling a house blla blla', 15, CAST(0 AS bit), CAST(0 AS bit), CAST(0 AS bit), CAST(1 AS bit), 30.899999999999999E0, 15.5E0, N'00e0ad26-5df2-45a8-a929-dde8f9c429c3', N'15863', 150000.0E0, 150, N'New York', N'83rd Street', 186, N'Selling House');
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id', N'Baths', N'Beds', N'BuildingType', N'CategoryId', N'City', N'County', N'CreatedAt', N'Description', N'HouseNumber', N'IsActive', N'IsDeleted', N'IsPrioritize', N'IsPublished', N'Latitude', N'Longitute', N'OwnerId', N'PostalCode', N'Price', N'Size', N'State', N'Street', N'StreetNumber', N'Title') AND [object_id] = OBJECT_ID(N'[Post]'))
SET IDENTITY_INSERT [Post] OFF;
Failed executing DbCommand (25ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id', N'Baths', N'Beds', N'BuildingType', N'CategoryId', N'City', N'County', N'CreatedAt', N'Description', N'HouseNumber', N'IsActive', N'IsDeleted', N'IsPrioritize', N'IsPublished', N'Latitude', N'Longitute', N'OwnerId', N'PostalCode', N'Price', N'Size', N'State', N'Street', N'StreetNumber', N'Title') AND [object_id] = OBJECT_ID(N'[Post]'))
SET IDENTITY_INSERT [Post] ON;
INSERT INTO [Post] ([Id], [Baths], [Beds], [BuildingType], [CategoryId], [City], [County], [CreatedAt], [Description], [HouseNumber], [IsActive], [IsDeleted], [IsPrioritize], [IsPublished], [Latitude], [Longitute], [OwnerId], [PostalCode], [Price], [Size], [State], [Street], [StreetNumber], [Title])
VALUES (1, 3, 5, 1, 1, N'New York', N'New Work', '2022-08-04T10:58:44.5986172+02:00', N'We are selling a house blla blla', 15, CAST(0 AS bit), CAST(0 AS bit), CAST(0 AS bit), CAST(1 AS bit), 30.899999999999999E0, 15.5E0, N'00e0ad26-5df2-45a8-a929-dde8f9c429c3', N'15863', 150000.0E0, 150, N'New York', N'83rd Street', 186, N'Selling House');
IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'Id', N'Baths', N'Beds', N'BuildingType', N'CategoryId', N'City', N'County', N'CreatedAt', N'Description', N'HouseNumber', N'IsActive', N'IsDeleted', N'IsPrioritize', N'IsPublished', N'Latitude', N'Longitute', N'OwnerId', N'PostalCode', N'Price', N'Size', N'State', N'Street', N'StreetNumber', N'Title') AND [object_id] = OBJECT_ID(N'[Post]'))
SET IDENTITY_INSERT [Post] OFF;
Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Post_AspNetUsers_OwnerId". The conflict occurred in database "Team3UberMain", table "dbo.AspNetUsers", column 'Id'.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:4e393a1b-a11d-4a8d-a2bb-646dd3c14e58
Error Number:547,State:0,Class:16
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Post_AspNetUsers_OwnerId". The conflict occurred in database "Team3UberMain", table "dbo.AspNetUsers", column 'Id'.
The statement has been terminated.
PM> Add-Migration Init
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
This is the class responsible for seeding the data (focus on AddUsers and AddPosts) :
public static class AddData
{
private static List<string> NamesList {
get {
return new List<string>("Liam,Noah,Oliver,Elijah,James,...,William,Benjamin".Split(","));
}
}
private static List<string> GetSurnamesList(int i = 0) {
string[] surnames = "Smith,Johnson,Williams,Brown,...,Tang,Archer".Split(",");
if (i > 0) Rotate(ref surnames, i);
return new List<string>(surnames);
}
private static int NrOfUsers = 0;
public static void AddUsers(ModelBuilder mb){
List<string> Names = NamesList;
List<string> Surnames = GetSurnamesList();
List<User> UsersList = new List<User>();
for (int i = 0; i < Names.Count; i++) {
string name = Names[i];
string surname = Surnames[i];
string phoneNumber = "0"+(44000000+i+NrOfUsers);
DateTime dateTime = DateTime.Now;
int userId = i+NrOfUsers;
string emailDomain = i % 3 == 0 ? "#gmail.com" : (i % 3 == 1 ? "#hotmail.com" : "#outlook.com");
string email = name + surname + emailDomain;
string password = name +surname +"123.";
string hash = HashPassword(password);
User u = new User
{
Email = email,
NormalizedEmail = email.ToUpper(),
EmailConfirmed = true,
UserName = email,
NormalizedUserName = email.ToUpper(),
UserId = userId,
FirstName = name,
LastName = surname,
Password = password,
PasswordHash = hash,
ConfirmPassword = password,
PhoneNumber = phoneNumber,
DateOfBirth = dateTime,
LockoutEnabled = true,
IsDeleted = false,
};
UsersList.Add(u);
}
mb.Entity<User>().HasData(UsersList);
NrOfUsers += Names.Count;
}
public static void AddAgents(ModelBuilder mb)
{
List<string> Names = NamesList;
List<string> Surnames = GetSurnamesList(1);
List<Agent> AgentsList = new List<Agent>();
for (int i = 0; i < Names.Count; i++)
{
string name = Names[i];
string surname = Surnames[i];
string phoneNumber = "0" + (44555000 + i+ NrOfUsers);
DateTime dateTime = DateTime.Now;
int userId = i+NrOfUsers;
string emailDomain = i % 3 == 0 ? "#gmail.com" : (i % 3 == 1 ? "#hotmail.com" : "#outlook.com");
string email = name + surname + emailDomain;
string password = name + surname + "123.";
string hash = HashPassword(password);
Agent a = new Agent
{
Email = email,
NormalizedEmail = email.ToUpper(),
EmailConfirmed = true,
UserName = email,
NormalizedUserName = email.ToUpper(),
UserId = userId,
FirstName = name,
LastName = surname,
Password = password,
PasswordHash = hash,
ConfirmPassword = password,
PhoneNumber = phoneNumber,
DateOfBirth = dateTime,
LockoutEnabled = true,
IsDeleted = false,
AgentId = 100000 + i + NrOfUsers
};
AgentsList.Add(a);
}
mb.Entity<Agent>().HasData(AgentsList);
NrOfUsers += Names.Count;
}
public static void AddCategorys(ModelBuilder mb) {
mb.Entity<Category>().HasData(
new Category() { Id = 1, CategoryName = "Land", },
new Category() { Id = 2, CategoryName = "Apartment" },
new Category() { Id = 3, CategoryName = "House" },
new Category() { Id = 4, CategoryName = "Farm" },
new Category() { Id = 5, CategoryName = "Barn" },
new Category() { Id = 6, CategoryName = "Flat" },
new Category() { Id = 7, CategoryName = "Penthouse" }
) ;
}
public static void AddPosts(ModelBuilder mb)
{
mb.Entity<Post>().HasData(
new Post
{
Id = 1,
Title = "Selling House",
Price = 150000,
State = "New York",
City = "New York",
PostalCode = "15863",
Street = "83rd Street",
HouseNumber = 15,
StreetNumber = 186,
County = "New Work",
CategoryId = 1,
// // todo : mi ndrreq owner id se osht string i gat
OwnerId = "00e0ad26-5df2-45a8-a929-dde8f9c429c3",
Description = "We are selling a house blla blla",
Longitute = 15.5,
Latitude = 30.9,
BuildingType = 1,
Size = 150,
Beds = 5,
Baths = 3,
CreatedAt = DateTime.Now,
IsPrioritize = false,
// TODO: add images and sponsored
IsPublished = true
}
);
}
private static void Rotate<T>(ref T[] array, int shiftCount)
{
if (shiftCount == 0) return;
T[] backupArray = new T[array.Length];
for (int index = 0; index < array.Length; index++)
{
backupArray[(index + array.Length + shiftCount % array.Length) % array.Length] = array[index];
}
array = backupArray;
}
private static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
}
This are the user and post models:
public class User : IdentityUser
{
public int UserId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string ConfirmPassword { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
public bool IsDeleted { get; set; }
[Required]
public bool IsActive { get; set; }
public List<Post> Posts { get; set; }
//public Guid ResetToken { get; set; }
}
public class Post : BaseAttributes
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
public double Price { get; set; }
[Required]
public string State { get; set; }
[Required]
public string City { get; set; }
public string PostalCode { get; set; }
public string Street { get; set; }
public int HouseNumber { get; set; }
public int StreetNumber { get; set; }
public string County { get; set; }
public int? CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
public string OwnerId { get; set; }
[ForeignKey("OwnerId")]
public User Owner { get; set; }
[Required]
public string Description { get; set; }
[Required]
public double Longitute { get; set; }
[Required]
public double Latitude { get; set; }
[Required]
public int BuildingType { get; set; }
[Required]
public int Size { get; set; }
[Required]
public int Beds { get; set; }
[Required]
public int Baths { get; set; }
[Required]
public DateTime CreatedAt { get; set; } = DateTime.Now;
public bool IsPrioritize { get; set; }
public List<Image> Images { get; set; }
public List<Sponsored> Sponsored { get; set; }
public bool IsPublished { get; set; } = false;
public virtual ICollection<Taken_By_Relation> Taken_by_list { get; set; }
}
This is the ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<User> User { get; set; }
public DbSet<Agent> Agent { get; set; }
public DbSet<SimpleUser> SimpleUser { get; set; }
public DbSet<Post> Post { get; set; }
public DbSet<Image> Image { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<Agent_Post_CounterOffer> Agent_Post_CounterOffer { get; set; }
public DbSet<CounterOffer> CounterOffer { get; set; }
public DbSet<FeedBack> FeedBack { get; set; }
public DbSet<Salary> Salary { get; set; }
public DbSet<Taken_By_Relation> Taken_By_Relation { get; set; }
public DbSet<Given_By_Relation> Given_By_Relation { get; set; }
public DbSet<Sponsored> Sponsored{ get; set; }
//public DbSet<Invite> Invite{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
AddData.AddUsers(modelBuilder);
AddData.AddAgents(modelBuilder);
AddData.AddCategorys(modelBuilder);
AddData.AddPosts(modelBuilder);
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Agent_Post_CounterOffer>().HasNoKey();
modelBuilder.Entity<Given_By_Relation>().HasNoKey();
modelBuilder.Entity<ChangePasswordViewModel>().HasNoKey();
modelBuilder.Entity<Salary>().HasNoKey();
//modelBuilder.Entity<Agent_Post_CounterOffer>().HasKey(ap => new { ap.AgentId, ap.PostId, ap.CounterOfferId });
//modelBuilder.Entity<Given_By_Relation>().HasKey(ap => new { ap.Given_By, ap.JobId, ap.PostId });
//modelBuilder.Entity<Taken_By_Relation>().HasKey(ap => new { ap.Taken_By, ap.JobId, ap.PostId });
}
}

How to restructure an Object in C# using LINQ?

I have a data set as follows:
[
{
"Id": 1,
"Country": "Uruguay",
"Name": "Foo",
"Status": "Completed",
},
{
"Id": 2,
"Country": "Uruguay",
"Name": "Foo",
"Status": "Completed",
},
{
"Id": 3,
"Country": "Germany",
"Name": "Foo",
"Status": "Completed",
},
]
I want to transform and sort it by Country so that it looks as follows:
[
{
"Country": "Uruguay",
"Details": [
{
"Id": 1,
"Name": "Foo",
"Status": "Completed",
},
{
"Id": 2,
"Name": "Foo",
"Status": "Completed",
},
],
},
{
"Country": "Germany",
"Details": [
{
"Id": 3,
"Name": "Foo",
"Status": "Completed",
},
],
},
],
These are the classes in C#:
public class Countries {
public int Id { get; set; }
public string Country { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
public class Details {
public int Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
public class CountryList {
public string Country { get; set; }
public List<Details> Details { get; set; }
}
Some of what I have tried looks as followed:
var foo = countries
.GroupBy(x => new Details { Id = x.Id, Name = x.Name, Status = x.Status })
.Select( y => new CountryList
{
// Country = y.Key.
}
var foo = countries
.GroupBy(x => x.Country)
.Select( y => new CountryList
{
// Country = y.Key.
Details = y.GroupBy(a => new Details
{
Id = a.Id,
Name = a.Name,
Status = a.Status
}).ToList()
}
I am having trouble working out how to use LINQ to solve this. I have done a handful of GroupBy operations in the past, but I wasn't able to work this one out. How do I transform my dataset into the desired result?
You do not need second GroupBy
var foo = countries
.GroupBy(x => x.Country)
.Select(y => new CountryList
{
Country = y.Key,
Details = y.Select(a => new Details
{
Id = a.Id,
Name = a.Name,
Status = a.Status
}).ToList()
};
You can take advantage of the .GroupBy() overload that lets you define a resultSelector to create your CountryLists and populate their Details:
var countries = new List<Countries>
{
new() { Id = 1, Country = "Uruguay", Name = "Foo", Status = "Completed" },
new() { Id = 2, Country = "Uruguay", Name = "Foo", Status = "Completed" },
new() { Id = 3, Country = "Germany", Name = "Foo", Status = "Completed" },
};
List<CountryList> countryList = countries
.GroupBy(
c => c.Country,
( country, matches ) => new CountryList()
{
Country = country,
Details = matches.Select(match => new Details
{
Id = match.Id,
Name = match.Name,
Status = match.Status
}).ToList()
})
.ToList();
, ( country, matches ) => new CountryList() { ... } being the resultSelector.
Example fiddle here.
try this
var orig = JsonConvert.DeserializeObject<List<Countries>>(json);
List<CountryList> countries = orig.GroupBy(o => o.Country)
.Select(x => new CountryList {
Country = x.Key,
Details = x.Select(o => new Details {Id=o.Id,Name=o.Name,Status=o.Status} ).ToList()
}).ToList();

hbm2ddl not working for some entity class in old claimed working source code

We have received claimed working source code. In code, all the entity model classes (hbm2java) are auto generated by Hibernate Tools 4.0.0 (checked by generated class java docs). We are trying to perform reverse engineering to generate database schema from models with mysql databse.
MySQL : 5.1.46-community
MySQL Connector : mysql-connector-java-5.1.46
Hibernate : Hibernate3
Here we are facing many errors:
Too many key parts specified; max 16 parts allowed
I am pasting the code of one such Entity class for which we are getting above error
#Entity
#Table(name = "ABC")
public class Abc implements java.io.Serializable {
private AbcId id;
public Abc() {
}
public Abc(AbcId id) {
this.id = id;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "a", column = #Column(name = "A", nullable = false)),
#AttributeOverride(name = "b", column = #Column(name = "B", nullable = false, length = 10)),
#AttributeOverride(name = "c", column = #Column(name = "C", nullable = false, length = 2)),
#AttributeOverride(name = "d", column = #Column(name = "D", nullable = false)),
#AttributeOverride(name = "e", column = #Column(name = "E", nullable = false, precision = 12)),
#AttributeOverride(name = "f", column = #Column(name = "F", nullable = false, precision = 12)),
#AttributeOverride(name = "g", column = #Column(name = "G", nullable = false, length = 400)),
#AttributeOverride(name = "h", column = #Column(name = "H", length = 400)),
#AttributeOverride(name = "i", column = #Column(name = "I", nullable = false, length = 1)),
#AttributeOverride(name = "j", column = #Column(name = "J", nullable = false, length = 2)),
#AttributeOverride(name = "k", column = #Column(name = "K", nullable = false, length = 1)),
#AttributeOverride(name = "l", column = #Column(name = "L", nullable = false, length = 100)),
#AttributeOverride(name = "m", column = #Column(name = "M", length = 100)),
#AttributeOverride(name = "n", column = #Column(name = "N", nullable = false, length = 23)),
#AttributeOverride(name = "o", column = #Column(name = "O", nullable = false, length = 100)),
#AttributeOverride(name = "p", column = #Column(name = "P", length = 23)),
#AttributeOverride(name = "q", column = #Column(name = "Q", length = 100)),
#AttributeOverride(name = "r", column = #Column(name = "R", nullable = false, length = 100)) })
public AbcId getId() {
return this.id;
}
public void setId(AbcId id) {
this.id = id;
}
}
This is a auto generated class by Hibernate Tools 4.0.0

Spring Data JPA joining two or more entites

I have three entities,
#Entity
public class Deck {
#Id
private int id;
private int number;
private String name;
#OneToMany(mappedBy = "deck")
private Set<Lab> labs;
//getter and setter methods
}
#Entity
public class Lab {
#Id
private int id;
private String name;
#ManyToOne
private Deck deck;
#OneToMany(mappedBy = "lab")
private Set<LabBooking> labBooking;
//getter and setter methods
}
#Entity
public class LabBooking {
#Id
private int id;
private Date startTime;
private Date endTime;
#ManyToOne
private Lab lab;
//getter and setter methods
}
Following is the LabRepository,
public interface LabRepository extends CrudRepository<Lab, Integer>{
#Query("SELECT l FROM Lab l JOIN l.labBooking lb WHERE l.deck.id = :deckId AND lb.startTime > '2016-02-24 15:00:00'")
List<Lab> findLabs(#Param("deckId") int deckId);
}
I am trying to retrieve the list of Labs in a deck which are occupied from a particular time.
When I execute the equivalent query (SELECT * FROM lab l JOIN lab_book lb ON l.id = lb.lab_id WHERE l.deck_id = 9999 AND lb.start_time > '2016-02-24 15:00:00') in MySQL, I am getting the following result
id name deck_id id end_time start_time lab_id
9001 Lab One 9999 5 2016-02-24 17:00:00 2016-02-24 16:00:00 9001
In the spring application I am getting the following result,
[{
"lab_id": 9001,
"lab_name": "Lab One",
"lab_booking": [{
"id": 4,
"start_time": "2016-02-24 15:00:00",
"end_time": "2016-02-24 16:00:00"
}, {
"id": 5,
"start_time": "2016-02-24 16:00:00",
"end_time": "2016-02-24 17:00:00"
}, {
"id": 3,
"start_time": "2016-02-24 14:00:00",
"end_time": "2016-02-23 14:30:00"
}]
}]
The Lab object was supposed to contain only the booking id 5, instead it shows all the ids.
If the sql query return 5 records, then the repository returns 5 Lab objects which are duplicate. What may be the issue?
Seems that your missing distinct.
SELECT distinct l FROM Lab l JOIN l.labBooking lb WHERE l.deck.id = :deckId AND lb.startTime > '2016-02-24 15:00:00'"