How do I insert a string to a StringBuffer?

package org.kodejava.lang;

public class StringBufferInsert {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("kodeava");
        System.out.println("Text before        = " + buffer);

        //  |k|o|d|e|a|v|a|....
        //  0|1|2|3|4|5|6|7|...
        //
        // From the above sequence you can see that the index of the
        // string is started from 0, so when we insert a string in
        // the fourth offset it means it will be inserted after the
        // "e" letter. There are other overload version of this
        // method that can be used to insert other type of data such
        // as char, int, long, float, double, Object, etc.
        buffer.insert(4, "j");
        System.out.println("After first insert = " + buffer);

        // Here we insert a string to the StringBuffer at index 8
        buffer.insert(8, " examples");
        System.out.println("Final result       = " + buffer);
    }
}

The program will print the following output:

Text before        = kodeava
After first insert = kodejava
Final result       = kodejava examples

How do I store object in Hibernate?

This example shows you how to store or save Hibernate object to database. The basic steps in creating application in Hibernate will be:

  • Creates the POJO
  • Create hibernate mapping file
  • Register the mapping file in hibernate configuration
  • Create a simple service class to store the object

In this example we’ll create a class called Label, this class is about a record label company. This class has the id, name, created and modified properties. Their types in order are Long, String, java.util.Date and java.util.Date.

Hibernate is an Object-Relational-Mapping (ORM) technology, which basically means how a Java object is mapped to a relational database model/table. Because of this, it needs a mapping file to map the object properties to table columns. The mapping file usually named in the format of Label.hbm.xml, the class name with hbm.xml suffix. And for Hibernate application recognize the object, the mapping file should be registered in hibernate configuration file (hibernate.cfg.xml).

We have a brief introduction about Hibernate class and configuration structure. Let’s jump to the working example. First we create the mapping file, and then we create the classes.

Create Label.hbm.xml mapping file.

In a maven project this file must be placed under the resources directory. In this example we place it in the org/kodejava/hibernate/mapping directory.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.kodejava.hibernate.model.Label" table="labels">
        <id name="id" column="id">
            <generator class="identity" />
        </id>
        <property name="name" not-null="true" />
        <property name="created" column="created" type="timestamp" />
        <property name="modified" column="modified" type="timestamp" />
    </class>
</hibernate-mapping>

Create Label.java class.

package org.kodejava.hibernate.model;

import java.util.Date;

public class Label {
    private Long id;
    private String name;
    private Date created;
    private Date modified;

    // Getters & Setters 

    @Override
    public String toString() {
        return "Label{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", created=" + created +
            ", modified=" + modified +
            '}';
    }
}

Create the LabelService.java class.

This class will handle the CRUD operation for our Label entity. In this example we start with the create/insert operation.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

public class LabelService {
    public void saveLabel(Label label) {
        // To save an object we first get a session by calling 
        // getCurrentSession() method from the SessionFactoryHelper class. 
        // Next we create a new transaction, save the Label object and 
        // commit it to database,
        Session session = SessionFactoryHelper.getSessionFactory()
                .getCurrentSession();

        session.beginTransaction();
        session.save(label);
        session.getTransaction().commit();
    }
}

Create the InsertDemo.java class.

package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

import java.util.Date;

public class InsertDemo {
    public static void main(String[] args) {
        LabelService service = new LabelService();

        // Creates a Label object we are going to be stored in the database.
        // We set the name, modified by and modified date information.
        Label label = new Label();
        label.setName("Sony Music");
        label.setCreated(new Date());

        // Call the LabelManager saveLabel method.
        service.saveLabel(label);
    }
}

Register mapping file in hibernate.cfg.xml.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <!-- Mapping to hibernate mapping files -->
        <mapping resource="org/kodejava/hibernate/mapping/Label.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

We have the code and the mapping file done. To register the mapping file in hibernate configuration file you can see the How do I create Hibernate’s SessionFactory? example. The example also tells you how to create the SessionFactoryHelper class to obtain Hibernate’s SessionFactory.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I insert a string in the StringBuilder?

package org.kodejava.lang;

public class StringBuilderInsert {
    public static void main(String[] args) {
        StringBuilder alphabets = new StringBuilder("abcdfghopqrstuvwxyz");
        System.out.println("alphabets = " + alphabets);

        //  |a|b|c|d|f|g|h|i|....
        //  0|1|2|3|4|5|6|7|8|...
        //
        // From the above sequence you can see that the index of the string is
        // started from 0, so when we insert a string in the fourth offset it
        // means it will be inserted after the "d" letter. There are other overload
        // version of this method that can be used to insert other type of data
        // such as char, int, long, float, double, Object, etc.
        alphabets.insert(4, "e");
        System.out.println("alphabets = " + alphabets);

        // Here we insert an array of characters to the StringBuilder.
        alphabets.insert(8, new char[] {'i', 'j', 'k', 'l', 'm', 'n'});
        System.out.println("alphabets = " + alphabets);
    }
}

The result of the code snippet above:

alphabets = abcdfghopqrstuvwxyz
alphabets = abcdefghopqrstuvwxyz
alphabets = abcdefghijklmnopqrstuvwxyz

How do I insert a record into database table?

In this example you’ll learn how to create a program to insert data into a database table. To insert a data we need to get connected to a database. After a connection is obtained you can create a java.sql.Statement object from it, and using this object we can execute some query strings.

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertStatementExample {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // Create a statement object.
            Statement stmt = connection.createStatement();
            String sql = "INSERT INTO book (isbn, title, published_year) " +
                    "VALUES ('978-1617293566', 'Modern Java in Action', 2019)";

            // Call execute() method of the statement object and pass the
            // query.
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Below is the script from creating the book table.

CREATE TABLE `book`
(
    `id`             bigint(20) unsigned                  NOT NULL AUTO_INCREMENT,
    `isbn`           varchar(50) COLLATE utf8_unicode_ci  NOT NULL,
    `title`          varchar(100) COLLATE utf8_unicode_ci NOT NULL,
    `published_year` int(11)                                       DEFAULT NULL,
    `price`          decimal(10, 2)                       NOT NULL DEFAULT '0.00',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8
  COLLATE = utf8_unicode_ci;

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.1.0</version>
</dependency>

Maven Central