How do I insert a string to a StringBuffer?

package org.kodejava.example.lang;

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

        //  |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.
        sb.insert(4, "j");
        System.out.println("After first insert = " + sb.toString());

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

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 the Hibernate mapping file
  • Register the mapping file in the Hibernate configuration
  • Create a simple manager 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 attributes. Their types in order are Integer, String, java.util.Date and java.util.Date.

Hibernate is an Object Relation Mapping technology which basically means how an object is mapped to a relational database model. 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 the Hibernate configuration hibernate.cfg.xml file.

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

<?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.example.hibernate.model.Label" table="labels">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" not-null="true"/>
        <property name="created" column="created" type="timestamp"/>
        <property name="modified" column="modified" type="timestamp"/>
    </class>
</hibernate-mapping>
package org.kodejava.example.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 +
            '}';
    }
}
package org.kodejava.example.hibernate.app;

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

public class LabelManager {
    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();
    }
}
package org.kodejava.example.hibernate.app;

import org.kodejava.example.hibernate.model.Label;

import java.util.Date;

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

        // Creates a Label object we are going to 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.
        manager.saveLabel(label);
    }
}

We have the code and the mapping file done. To register the mapping file in the 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 the Hibernate’s SessionFactory.

Maven Dependencies

<dependencies>
    <!--https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.4.1.Final/hibernate-core-5.4.1.Final.jar-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <!--https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-ehcache/5.4.1.Final/hibernate-ehcache-5.4.1.Final.jar-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <!--https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

Maven Central
Maven Central

How do I insert a string in the StringBuilder?

package org.kodejava.example.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 string.

package org.kodejava.example.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 = "root";
    private static final String PASSWORD = "";

    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 books (isbn, title, published_year) " +
                "VALUES ('9781617291999', 'Java 8 in Action', 2015)";

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

Below is the script from creating the books table.

CREATE TABLE `books` (
  `isbn` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `published_year` int(11) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Maven dependencies

<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

Maven Central