Last weekend, Kids had their talent show at Tamil school. Happy to see all the kids in school, participated and performed well.
Spring is here in Canada. Its time for Cherry Blossoms. We visited High park and Kariya Park. Happy to see the trees with pink/rose colors. Read more here about it. https://en.wikipedia.org/wiki/Cherry_blossom
Attended KanchiLUG meet on sunday morning. If you know tamil and in Tech, dont miss the thoughtful discussions at KanchiLUG meet, every sunday. Check the calendar here – https://kaniyam.com/events/
At the meet, we discussed collecting open data for tamil. After the meet, wrote a code for scrapping for wordpress code and started to scrap the contents in CC license. Working on adding more features like resuming when stopped, alerts etc. Will share code and data soon.
Gave a online Talk on Tamil data collection on 05.05.2025. Will share the video soon.
I am using facebook in computer. Annoyed by the short videos, advertisements, was looking for a way to get cleaner content. I want only the content from my friends, the pages I follow and the groups I am in. I dont want any other thing. Fortunately, found a nice firefox plugin. fbcleaner – https://addons.mozilla.org/en-US/firefox/addon/fbcleaner/
With this plugin, the timeline is a breeze. It is available only for computer. Use this and save time.
By using computer, to access social media, I am more mindful. Not spending too much time there.
Completed reading two books. I am enjoying reading the physical books nowadays. 1. எம்டன் செல்வரத்தினம், சென்னையர் கதைகள் 2. நரகத்தில் இருந்து ஒரு குரல் – சாரு நிவேதிதா
Took G1 test for car driving. It is like LLR in india. After getting G1, we can learn driving car. After some 8 months, we can get G2 license, to drive car alone. Will learn car driving soon.
Last two weeks went super busy with office work, reading, library visits and few events.
Reading:
Completed reading the original book and rewritten version of “பெண் ஏன் அடிமையானாள்?” “Why women became slave?” by originally written by Periyar. That book describes why Indian women are still slaves of family, society due to various reasons like marriage, childcare etc.
The sad part is, even though that book was written few decades ago, it is still relevant.
Like any other devotional books/stories are retold for every generation, this book should also be rewritten, once in every 10-20 years and it should be told on all modern formats like audio books, drama, shortfilms, shorts etc.
Reviewing and editing that rewritten version is one of the most satisfying action I did this year. Hope we can release this as a print edition and free ebook edition. Checking with few contacts to publish this. Will share the progress soon.
Still reading the book “Attention Span”. May take few weeks to complete.
Easter: Kids got some 4 days holidays due to Easter. They all went for a Easter egg hunting event.
HeartComonos: At HeartComonos, a social non profit organization, is conducting many free events here. Participated on a Bollywood dance event with family. Celebrated its lead Hardy’s birthday, along with fun filled dancing. Helped to capture the wonderful moments with Camera.
Library visit:
On the weekend, we visited Mississauga Central Library. It is one of the best places, as a family, we like to go anytime. Just being surrounded by million books itself a great feeling. Viyan is reading a lot. Iyal is still trying to read. Paari is yet to learn reading, but he can turn pages of books one by one for many hours. There are good comics books available. Both Iyal and Paari are creating their own stories, just by seeing and turning the pages. What else we need for kid’s mind to be filled with imagination?
Upcoming talk on Open Licensed Tamil dataset collection: On May 05 2025, I will be giving an online talk on curation of open licensed tamil dataset. Preparing for the talk along with collecting open data in Tamil.
KanchiLUG meets: Every sunday IST evening hours, ( my mornings) are going useful with interesting discussions on Linux, Free/Open Source software etc.
Tamil Skills contest for kids: Last saturday, attended a contest for kids with viyan. Good to see that around 100+ kids participated on the contest on Skills for Tamil reading,writing and speaking. viyan participated with last min preparation. Next year, hope all three kids will attend. Happy to see many friends like Natkeeran, Suba, Kent, Selvanayaki madam.Took care of capturing some wonderful moments of the events.
After the event, spent few hours in a library at Toronto Downtown. I skimmed on few books on black/white photography, Instagram posting, video making and Toronto Photographers collection etc. Discussing many things with viyan is one of my favourite things. When we travel along, we talk about many things like world history, war, mythology, comics, manga, atheism, Tamilnadu political history etc.
ComicCon Mississauga: Sunday, attended an event for Comics and Toy Collections. Around 100 sellers were selling old comics books, unopened hero toys. There were many kids buying those stuffs. I was wondering to see, there were many adults standing in line, exploring the old comics and toys, and buying them with wide open eyes.
First they create a cha rector, then bring as comic books, then toys, then computer games, then graphic novel, then text novel, then movies. This is how all the childhood characters are becoming immortal. The business behind this is very huge. Thinking why we the Indians can not bring such huge cycle of business, even though we have tons of stories. Among all the mythological stories, there are very little for children. We have to create more stories and do business with them.
Nithya’s Video series on GenAI
Nithya started text series on GenAI at Kaniyam.com and a video series on her youtube channel, in Tamil. We had some good outdoor shooting for the intro video. Released the first video here
1.Create a tuple containing the names of three fruits. Print the tuple and its type.
2.Given a tuple t = ("apple", "banana", "cherry"), access and print the second element.
3.Unpack the tuple t = (1, 2, 3) into variables a, b, and c, and print the variables.
4.Concatenate two tuples t1 = (1, 2) and t2 = (3, 4) and print the result.
5.Create a tuple t = ("repeat",) and repeat it three times. Print the resulting tuple.
6.Given a tuple t = (1, 2, 3, 2, 2, 4), count the number of times the number 2 appears.
7.Given a tuple t = ("a", "b", "c", "d"), find the index of the element "c".
8.Check if the element 5 is present in the tuple t = (1, 2, 3, 4)
9.Find and print the length of the tuple t = ("one", "two", "three").
10.Slice the tuple t = (0, 1, 2, 3, 4, 5) to obtain a sub-tuple containing only the elements from index 2 to 4.
11.Create a nested tuple representing a 2D point (x, y) = ((1, 2), (3,
4)). Access and print the second coordinate of the second point.
12.Try to change the value of the first element in the tuple t = (1, 2, 3) and observe what happens.
13.Convert a list l = [1, 2, 3] to a tuple and print the result. Then convert a tuple t = (4, 5, 6) to a list and print the result.
14.Create a tuple with a single item 5 and verify its type is a tuple.
15.Iterate over the tuple t = ("ParottaSalna", "is", "good") and print each element.
16.Convert the string "hello" into a tuple of characters.
17.Convert a dictionary d = {"one": 1, "two": 2} into a tuple of its items.
18.Write a function that takes a tuple of numbers and returns the sum of the numbers.
19.Use tuples as keys in a dictionary to represent points on a grid. For example, grid = {(0, 0): "origin", (1, 2): "point A"}.
1.Write a function greet that takes a name as an argument and prints a greeting message.
2.Write a function sum_two that takes two numbers as arguments and returns their sum.
3.Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.
4.Write a function find_max that takes two numbers as arguments and returns the larger one.
5.Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.
6.Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.
7.Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.
Today, I want to share something unexpected. To be honest, if someone had told me a month ago that I could do this, I wouldn’t have believed them. But here we are — I’ve finally released a Python package and dataset called TamilKavi. I still can’t believe I pulled it off, but it’s real!
I’d love to share the whole story with you. Many of you already know me — I write Tamil poetry and have even published two books. However, I faced font issues when trying to release them on Amazon and Kindle. Frustrated, I reached out to my community friend, Hari, and I asked them: “Bro, I want to release my Tamil poetry book on Amazon, but I’m stuck with font issues. Do you know anyone who can solve it?”
Hari referred me to Ayyanar Bro, and to me it’s a surprise, he was from Madurai — what a coincidence! We spoke almost four times a week for different reasons. I had already written about him and his portfolio website, which he built using Emacs & Org, so I won’t go into more details — you guys might find it repetitive.
Through Ayyanar Bro, I learned about the Tamil Kanchilung community and FreeTamilBooks, where I finally found a solution to my font issue. But here’s another twist — FreeTamilBooks required more poetry for my book release. Because I like to release that in FreeTamilBooks.Then another book on Amazon. That was another headache because, with my tight schedule, I barely had time to write.
While navigating all this, I discovered Tamilrulepy, a Python package with Tamil grammar rules. I was eager to learn more, and unexpectedly, I got an opportunity to contribute to it! That’s when I met Boopalan — another passionate tech enthusiast like me. He helped me write code for TamilRulePy and even invited me to contribute to TamilString, a Python package for documentation. I accepted his invitation and started working on it.
Then, during one of our conversations, I got an idea: why not develop my own Python package? And that’s how TamilKavi was born.
I shared my idea with Boopalan and invited him to build it as a team because, honestly, I’m no expert. But it wasn’t easy — we had to overcome countless challenges, especially since we were both preparing for our model exams and semester exams (he’s an MSc student, and I’m a BSc student). It was a tough time, but I didn’t give up. I studied, understood, and gradually started coding — not entirely on my own, of course.
Now, you might wonder — why build a website? Simple: to collect data from authors. But due to financial constraints, the data collected through the website idea transformed into a Google Form, and now it is a navigation button. It’s another story altogether. Since I had no time, I built a basic structure using Lovable.dev and handed it over to my juniors, Gagan & Rohith, who took care of the website.
The final result? Release of the Python package & website!
I must especially thank Praveen Bro — my community brother and mentor. Without hesitation, he offered me a subdomain. For me, that’s a huge deal, and I’m incredibly grateful!
“Okay thambi, enough of this English talk — why did you release the dataset?” When you ask me likewise.
Well, there’s a reason for that, too. I’ve seen Selvakumar Duraipandian Bro on LinkedIn about their post of numerous Tamil datasets on Hugging Face, including Thirukkural, Tholkappiyam, and more. I was truly inspired by his work. So, I release that as a Dataset.
Now, you might ask, “So, thambi, after all this talk, what does your package actually do?”
It’s simple — TamilKavi helps discover new Tamil poems. That’s all. Now your mind is
“Edhuka evalo seenu?”
Well, I’m not just a developer. The person who is are Tamil poet & tech enthusiast, it’s a crazy project. Through this journey, I’ve learned so much, especially about GitHub workflows.
When you feel this content is valuable, follow me for more upcoming Blogs.
1.Write a function that takes a string and returns a new string consisting of its first and last character.
2.Write a function that reverses a given string.
3.Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).
4.Write a function that returns every second character from a given string.
5.Write a function that replaces the middle third of a string with asterisks. If the length of the string is not divisible by 3, adjust the middle third accordingly.
6.Write a function that checks if a given string is a palindrome (reads the same backward as forward).
7.Given an email address, extract and return the domain.
Ans: How to find incase there are multiple occurrences? Loop?
8.Write a function that returns every third character from a given string.
9.Write a function that extracts and returns characters at even indices from a given string.
10.Write a function that skips every second character and then reverses the resulting string.
1.Create a variable named name and assign your name to it. Then print the value of the variable.
2.Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.
3.Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.
Ans:TypeError on 4th statement, because we're trying to concatenate integers (a, b, c) with strings
4.Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.
5.Define constants PI with appropriate values and print them.
Ans: constants are typically written in all uppercase letters with underscores separating words. However, Python does not enforce this, so constants are not truly immutable. You can still override.
6.Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.
Ans: ** is Squared
7.Define constants for the length and width of a rectangle. Calculate and print the area.
8.Define a constant for π (pi) and a variable for the radius. Calculate and print the circumference of the circle.
1.How do you print the string “Hello, world!” to the screen?
Ans: Using sep and end Parameters is preferred way.
2.How do you print the value of a variable name which is set to “Syed Jafer” or Your name?
Ans: Note the Variable is case sensitive
3.How do you print the variables name, age, and city with labels “Name:”, “Age:”, and “City:”?
Ans: Using keyword sep="," brings in , between the Variable Name and Value itself, so avoid
4.How do you use an f-string to print name, age, and city in the format “Name: …, Age: …, City: …”?
Ans: To insert variables directly into the string used f-string
Also, you can assign values to multiple variables in a single line as seen in 1st line
5.How do you concatenate and print the strings greeting (“Hello”) and target (“world”) with a space between them?
Ans: + is used to concat the items
6.How do you print three lines of text with the strings “Line1”, “Line2”, and “Line3” on separate lines?****
7.How do you print the string He said, "Hello, world!" including the double quotes?
Ans: To print quotes inside a string, you can use either single or double quotes to enclose the string and the other type of quotes inside it.
8.How do you print the string C:\Users\Name without escaping the backslashes?
Ans: you can also use a literal backslash "\" when using Concat or Try with 'r' to treat backslashes as literal characters
9.How do you print the result of the expression 5 + 3?
10.How do you print the strings “Hello” and “world” separated by a hyphen -?
11.How do you print the string “Hello” followed by a space, and then print “world!” on the same line?
12.How do you print the value of a boolean variable is_active which is set to True?
13.How do you print the string “Hello ” three times in a row?
14.How do you print the sentence The temperature is 22.5 degrees Celsius. using the variable temperature?
15.How do you print name, age, and city using the .format() method in the format “Name: …, Age: …, City: …”?
16.How do you print the value of pi (3.14159) rounded to two decimal places in the format The value of pi is approximately 3.14?
Ans: pi is the variable & .2f formats it as a floating-point number with 2 digits after the decimal
17.How do you print the words “left” and “right” with “left” left-aligned and “right” right-aligned within a width of 10 characters each?
@Entity – used to indicates the class is below to JPA entites.
@Table – is used to indicates the table name.
@MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {
private String firstName;
private String lastName;
// Constructors, getters, setters, other fields...
}
In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
By using @MappedSuperclass, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs.
This promotes code reusability and maintains a clean and structured entity hierarchy.
Primary Keys
Define a primary key using @Id.
Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other fields, getters, setters
}
Associations
It says the relationship between two entity class.
Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department",cascade=CascadeType.ALL)
private List<Employee> employees;
// Constructors, getters, setters, other fields...
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Constructors, getters, setters, other fields...
}
Cascading Operations
Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;
// Constructors, getters, setters, other fields...
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
// Constructors, getters, setters, other fields...
}
CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (Author) to the child entity (Book).
orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book entity should also be removed from the database
When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.
Author author = new Author();
author.setName("J.K. Rowling");
Book book1 = new Book();
book1.setTitle("Harry Potter and the Sorcerer's Stone");
book1.setAuthor(author);
Book book2 = new Book();
book2.setTitle("Harry Potter and the Chamber of Secrets");
book2.setAuthor(author);
author.setBooks(Arrays.asList(book1, book2));
// Cascading persist: Saving the author will also save both associated books.
entityManager.persist(author);
Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.
Validation
Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class. Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Title is required")
@Size(max = 100, message = "Title must be at most 100 characters")
private String title;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private List<Comment> comments;
// Constructors, getters, setters, other fields...
}
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Text is required")
@Size(max = 500, message = "Text must be at most 500 characters")
private String text;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
// Constructors, getters, setters, other fields...
}
Auditing
Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
@MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
@CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
@CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
@LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
@LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.
By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.
Enums and Enumerated Types
Use Java enums for fields with predefined values.
Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private TaskStatus status;
// other fields, getters, setters
}
public enum TaskStatus {
TODO, IN_PROGRESS, DONE
}
@Entity – used to indicates the class is below to JPA entites.
@Table – is used to indicates the table name.
@MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {
private String firstName;
private String lastName;
// Constructors, getters, setters, other fields...
}
In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
By using @MappedSuperclass, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs.
This promotes code reusability and maintains a clean and structured entity hierarchy.
Primary Keys
Define a primary key using @Id.
Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other fields, getters, setters
}
Associations
It says the relationship between two entity class.
Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department",cascade=CascadeType.ALL)
private List<Employee> employees;
// Constructors, getters, setters, other fields...
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Constructors, getters, setters, other fields...
}
Cascading Operations
Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;
// Constructors, getters, setters, other fields...
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
// Constructors, getters, setters, other fields...
}
CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (Author) to the child entity (Book).
orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book entity should also be removed from the database
When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.
Author author = new Author();
author.setName("J.K. Rowling");
Book book1 = new Book();
book1.setTitle("Harry Potter and the Sorcerer's Stone");
book1.setAuthor(author);
Book book2 = new Book();
book2.setTitle("Harry Potter and the Chamber of Secrets");
book2.setAuthor(author);
author.setBooks(Arrays.asList(book1, book2));
// Cascading persist: Saving the author will also save both associated books.
entityManager.persist(author);
Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.
Validation
Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class. Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Title is required")
@Size(max = 100, message = "Title must be at most 100 characters")
private String title;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private List<Comment> comments;
// Constructors, getters, setters, other fields...
}
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Text is required")
@Size(max = 500, message = "Text must be at most 500 characters")
private String text;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
// Constructors, getters, setters, other fields...
}
Auditing
Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
@MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
@CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
@CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
@LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
@LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.
By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.
Enums and Enumerated Types
Use Java enums for fields with predefined values.
Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private TaskStatus status;
// other fields, getters, setters
}
public enum TaskStatus {
TODO, IN_PROGRESS, DONE
}
I am going to create two entities. They are task and Todo. It has one to many, It means todo has many task. Create the field and getter and setter methods.
TodoList class
It has id, name and List<Task>. Create getter and setter method.
Then we create bidirectional relationship between todo have task. so we create mappedBy the todo object on task. so task can create foreign key for todo list.
@Entity
public class TodoList {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "todoList", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.EAGER)
private List<Task> taskList= new ArrayList<>();
@ManyToOne
@JoinColumn(name = "user_idn")
private Users users;
// no-arg constructor and getter and setter
}
Task class
It has id and name and todo object. Then we create getter and setter method.
The foreign key create in this table, because we mapped this todo object is mapped on that class. joinColumn name is the foreign key name.
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private boolean status;
// private Locale locale; // date and time
@ManyToOne
@JoinColumn(name = "todo_list_id")
private TodoList todoList;
}
Repository Interface
Simple that create two interface one for task and todo which can extend the JPARepository.
public interface TaskRepository extends JpaRepository<Task, Long> {
}
public interface TaskRepository extends JpaRepository<Task, Long> {
}
Then we enter into the a list, it have many task. That can be shown by this method. we get the list by id and we pass that list of task and new task to html.
@GetMapping("/{listId}")
public String viewTodoList(@PathVariable Long listId, Model model) {
TodoList todoList = todoListRepository.findById(listId)
.orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
model.addAttribute("todoList", todoList);
model.addAttribute("newTask", new Task());
return "tasks";
}
4. create the task from todo list
Then we press create task button on html. we got new task from getMapping that task pass through @modelAttribute. That list can save in repository.
// Add task to a todo list
@PostMapping("/{listId}/tasks")
public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
TodoList todoList = todoListRepository.findById(listId)
.orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
task.setTodoList(todoList);
taskRepository.save(task);
return "redirect:/todos/" + listId;
}
5. Toggle the task or not
Then we press todo checkbox it can be tick. Same find the task by taskId. That task setCompleted and save it again in task. Return redirect://todos/+listId, it redirect to getMapping or this Todo List.
// Toggle task completion status
@PostMapping("/{listId}/tasks/{taskId}/toggle")
public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
Task task = taskRepository.findById(taskId)
.orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
task.setCompleted(!task.isCompleted());
taskRepository.save(task);
return "redirect:/todos/" + listId;
}
6. delete the todo list
Then we press delete button from list on html. we remove from repository. Return the getMapping of current list.
@PostMapping("/{listId}/delete")
public String deleteTask(@PathVariable Long listId) {
taskRepository.deleteById(taskId);
return "redirect:/todos/" + listId;
}
7. delete the task from task list
Then we press delete button on html. We delete task from task repository. We return and redirect to getmapping of current task list.
@PostMapping("/{listId}/delete")
public String deleteTodoList(@PathVariable Long listId) {
todoListRepository.deleteById(listId);
return "redirect:/todos";
}
Controller full code
@Controller
@RequestMapping("/todos")
public class TodoController {
@Autowired
private TodoListRepository todoListRepository;
@Autowired
private TaskRepository taskRepository;
// Show all todo lists
@GetMapping
public String listTodoLists(Model model) {
model.addAttribute("todoLists", todoListRepository.findAll());
model.addAttribute("newTodoList", new TodoList());
return "todo-lists";
}
// Create new todo list
@PostMapping
public String createTodoList(@ModelAttribute TodoList todoList) {
todoListRepository.save(todoList);
return "redirect:/todos";
}
// Show tasks from todo list
@GetMapping("/{listId}")
public String viewTodoList(@PathVariable Long listId, Model model) {
TodoList todoList = todoListRepository.findById(listId)
.orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
model.addAttribute("todoList", todoList);
model.addAttribute("newTask", new Task());
return "tasks";
}
// Add task to a todo list
@PostMapping("/{listId}/tasks")
public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
TodoList todoList = todoListRepository.findById(listId)
.orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
task.setTodoList(todoList);
taskRepository.save(task);
return "redirect:/todos/" + listId;
}
// Toggle task completion status
@PostMapping("/{listId}/tasks/{taskId}/toggle")
public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
Task task = taskRepository.findById(taskId)
.orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
task.setCompleted(!task.isCompleted());
taskRepository.save(task);
return "redirect:/todos/" + listId;
}
// Delete a task
@PostMapping("/{listId}/tasks/{taskId}/delete")
public String deleteTask(@PathVariable Long listId, @PathVariable Long taskId) {
taskRepository.deleteById(taskId);
return "redirect:/todos/" + listId;
}
// Delete a todo list
@PostMapping("/{listId}/delete")
public String deleteTodoList(@PathVariable Long listId) {
todoListRepository.deleteById(listId);
return "redirect:/todos";
}
}
Html code
Html has two page one for todo list and another for task list.
Todo list.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Todo Lists</title>
<link rel="icon" type="image/x-icon" href="/aaeranLogo.ico" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<h1>My Todo Lists</h1>
<!-- Form to create new todo list -->
<form th:action="@{/todos}" th:object="${newTodoList}" method="post" class="mb-4">
<div class="input-group">
<input type="text" th:field="*{name}" class="form-control" placeholder="New list name" required>
<button type="submit" class="btn btn-primary">Create List</button>
</div>
</form>
<!-- display the todo list -->
<div th:each="todoList : ${todoLists}" class="card mb-3">
<div class="card-body">
<h2 class="card-title">
<a th:href="@{/todos/{id}(id=${todoList.id})}" th:text="${todoList.name}">List Name</a>
<span class="badge bg-secondary" th:text="${todoList.taskList.size()}">0</span>
</h2>
<form th:action="@{/todos/{id}/delete(id=${todoList.id})}" method="post" class="d-inline">
<button type="submit" class="btn btn-sm btn-danger">Delete List</button>
</form>
</div>
</div>
</div>
</body>
</html>
In this blog, we are going to deploy out spring boot application with PostgreSQL using to
Web site on render.com
PostgreSQl on neon.com
Create an Application
We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.
Frontent (Thyme Leaf)
I am going to create html that can integrate with thyme leaf.
Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.
Spring boot Controller layer
I create controller class which can map the html with java class.
@Controller
public class ControllerClass {
@GetMapping
public String getInitialisePage(Model model) {
String p = "ravana";
model.addAttribute("word",p);
return "index";
}
}
Create a Repository Interface
we are going to do dataBase configuaration and spring JPA here.
Configuration of Database and JPA
Configure the Database and JPA on Application.Properties.
Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.
Using Eclipse or Spring tool suit IDE
Right click on our project.
Run as -> run configurations
click the environment and set the name and value.
Eg. name = DATASOURCE_URL and value = our jbdc url
Eg. name = DATASOURCE_USERNAME and value = our username
Eg. name = DATASOURCE_PASSWORD and value = our Password
Create jar file from our project
When we create Spring boot project we have .mvn file. Delete the test related dependency and class.
./mvnw clean package
If not work copy this below code. This is work on linux only
export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
export SPRING_USERNAME="postgres"
export DATASOURCE_PASSWORD="1234"
//don't be panic as run again to run ./mvnw clean package
// else give this command
// remove the test depandancy and delete src/main/test.
// ./mvnw clean package
Create a docker file
Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.
# Use an official Maven image to build the Spring Boot app
FROM maven:3.8.4-openjdk-17 AS build
# Set the working working directory
WORKDIR /app
# Copy the pom.xml and install dependencies
COPY pom.xml .
RUN mvn dependency:go-offline
# Copy the source code and build the application
COPY src ./src
RUN mvn clean package -DskipTests # This will download the all depandencies
# Use an official OpenJDK image to run the application
FROM openjdk:17-jdk-slim
#Set the working directory
WORKDIR /app
# Copy the built JAR file from the build stage
COPY --from=build /app/target/file-name.jar .
# my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
# Expose port 8080
EXPOSE 8080
# Specify the command to run the application
ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
# change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
# ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
Create Docker image
After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.
Go to neon.tech, create account we got free 500MB space DB. Now create project and add.
Important is to get the configutation because we will use in application part.
postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
Select the environmental variable on render.com
DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
DATASOURCE_USERNAME=username
DATASOURCE_PASSWORD=password
Host the Web application
Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.
const observer = new MutationObserver(() => {
const heading = document.querySelector(".title-shortlink-container");
if (heading) {
// Create the button element
const button = document.createElement("button");
button.textContent = "Copy Text";
button.style.marginLeft = "10px"; // Add some spacing from the container
// Insert the button next to the .title-shortlink-container
heading.insertAdjacentElement("afterend", button);
// Add an event listener to copy the text
button.addEventListener("click", () => {
const textToCopy = heading.textContent.trim(); // Get only the container's text
navigator.clipboard.writeText(textToCopy).then(() => {
alert("Text copied: " + textToCopy);
}).catch(err => {
console.error("Failed to copy text: ", err);
});
});
observer.disconnect(); // Stop observing once the element is found
}
});
// Observe the document for dynamic changes
observer.observe(document.body, { childList: true, subtree: true });
Code Explanation :
Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
If the Heading is not null. Then we create the button and styles.
The Button is placed next to link. Use heading.insertAdjacentElement(“afterend”, button);
Button action create a function in addEventListener.
Get the link by heading.textContent and store in textToCopy
For copy the text use navigator.clipboard.writeText(textToCopy)
Then pop alert for the event.
if error catch throw error message.
Problem faced (dynamically loaded content)
First i use DOMContentLoaded. It cannot work in wiki.
Then i use Polling (Setintervel for a Certain time). It works partcially.
Then i use MutationObserver. I works perfectly to all pages.
INSERT statement to insert a new row into a table.
INSERT INTO table1(column1, column2, …)
VALUES (value1, value2, …);
In this syntax:
First, specify the name of the table (table1) that you want to insert data after the INSERT INTO keywords and a list of comma-separated columns (colum1, column2, ....).
Second, supply a list of comma-separated values in parentheses (value1, value2, ...) after the VALUES keyword. The column and value lists must be in the same order.
RETURNING clause
The INSERT statement has an optional RETURNING clause