mirror of
https://github.com/Microsoft/sql-server-samples.git
synced 2025-12-08 14:58:54 +00:00
New samples for Java and C#
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("*** SQL Server Columnstore demo ***");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create an example database
|
||||
System.out.print("Dropping and creating database 'Example_Columnstore' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [Example_Columnstore]; CREATE DATABASE [Example_Columnstore]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
// Insert 5 million rows into the table 'Table_with_5M_rows'
|
||||
System.out.print(
|
||||
"Inserting 5 million rows into table 'Table_with_5M_rows'. This takes ~15 seconds, please wait ... ");
|
||||
sql = new StringBuilder().append("USE Example_Columnstore; ")
|
||||
.append("WITH a AS (SELECT * FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS a(a))")
|
||||
.append("SELECT TOP(5000000)")
|
||||
.append("ROW_NUMBER() OVER (ORDER BY a.a) AS OrderItemId ")
|
||||
.append(",a.a + b.a + c.a + d.a + e.a + f.a + g.a + h.a AS OrderId ")
|
||||
.append(",a.a * 10 AS Price ")
|
||||
.append(",CONCAT(a.a, N' ', b.a, N' ', c.a, N' ', d.a, N' ', e.a, N' ', f.a, N' ', g.a, N' ', h.a) AS ProductName ")
|
||||
.append("INTO Table_with_5M_rows ")
|
||||
.append("FROM a, a AS b, a AS c, a AS d, a AS e, a AS f, a AS g, a AS h;").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute SQL query without a columnstore index
|
||||
long elapsedTimeWithoutIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITHOUT columnstore index: " + elapsedTimeWithoutIndex + "ms");
|
||||
|
||||
System.out.print("Adding a columnstore to table 'Table_with_5M_rows' ... ");
|
||||
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_5M_rows;";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute the same SQL query again after the columnstore index is added
|
||||
long elapsedTimeWithIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITH columnstore index: " + elapsedTimeWithIndex + "ms");
|
||||
|
||||
// Calculate performance gain from adding columnstore index
|
||||
System.out.println("Performance improvement with columnstore index: " + elapsedTimeWithoutIndex/elapsedTimeWithIndex + "x!");
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static long SumPrice (Connection connection){
|
||||
String sql = "SELECT SUM(Price) FROM Table_with_5M_rows;";
|
||||
long startTime = System.currentTimeMillis();
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
long elapsedTime = System.currentTimeMillis() - startTime;
|
||||
return elapsedTime;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerHibernateSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerHibernateSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>5.2.3.Final</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.DriverManager;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
|
||||
/**
|
||||
* Java CRUD sample with Hibernate and SQL Server
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433"; // update me
|
||||
String userName = "sa"; // update me
|
||||
String password = "your_password"; // update me
|
||||
String sampleDatabaseName = "SampleDB";
|
||||
|
||||
// Main entry point
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
app.runDemo();
|
||||
}
|
||||
|
||||
// Helper to run the demp app
|
||||
public void runDemo()
|
||||
{
|
||||
// Configure Hibernate logging to only log SEVERE errors
|
||||
@SuppressWarnings("unused")
|
||||
org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
|
||||
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.SEVERE);
|
||||
|
||||
System.out.println("**Java CRUD sample with Hibernate and SQL Server **\n");
|
||||
try {
|
||||
// We're creating the Hibernate configuration via code. An alternative is to use a 'hibernate.cfg.xml' file.
|
||||
Configuration cfg = createHibernateConfiguration();
|
||||
|
||||
// We're mapping POJO classes to Tables via Hibernate Annotations. An alternative is to use Hibernate mapping xml files.
|
||||
cfg.addAnnotatedClass(User.class);
|
||||
cfg.addAnnotatedClass(Task.class);
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this sample.
|
||||
createSampleDatabase();
|
||||
|
||||
// Create the Hibernate SessionFactory and Session.
|
||||
// This causes Hibernate to create Tables and Relationships in the database from our Annotated classes.
|
||||
try (SessionFactory sessionFactory = cfg.buildSessionFactory();
|
||||
Session session = sessionFactory.openSession()) {
|
||||
|
||||
System.out.println("Created database schema from Java classes.\n");
|
||||
session.beginTransaction();
|
||||
|
||||
// Create demo: Create a User instance and save it to the database
|
||||
User newUser = new User("Anna", "Shrestinian");
|
||||
session.save(newUser);
|
||||
System.out.println("Created User: " + newUser.toString());
|
||||
|
||||
// Create demo: Create a Task instance and save it to the database
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
|
||||
Task newTask = new Task("Ship Helsinki", sdf.parse("04-01-2017"));
|
||||
session.save(newTask);
|
||||
System.out.println("Created Task: " + newTask.toString());
|
||||
|
||||
// Association demo: Assign task to user
|
||||
newTask.setUser(newUser);
|
||||
session.save(newTask);
|
||||
System.out.println("Assigned Task: '" + newTask.getTitle() + "' to user '" + newUser.getFullName() + "'\n");
|
||||
|
||||
// Read demo: find incomplete tasks assigned to user 'Anna'
|
||||
System.out.println("Incomplete tasks assigned to 'Anna':");
|
||||
String hqlQuery = "from Task where isComplete = false and user.firstName = :paramFirstName";
|
||||
List<Task> incompleteTasks = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramFirstName", "Anna")
|
||||
.getResultList();
|
||||
for(Task theTask : incompleteTasks) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
|
||||
// Update demo: change the 'dueDate' of a task
|
||||
hqlQuery = "from Task";
|
||||
Task taskToUpdate = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList()
|
||||
.get(0); // get the first task
|
||||
System.out.println("\nUpdating task: " + taskToUpdate.toString());
|
||||
taskToUpdate.setDueDate(sdf.parse("06-30-2016"));
|
||||
session.save(taskToUpdate);
|
||||
System.out.println("dueDate changed: " + taskToUpdate.toString());
|
||||
|
||||
// Delete demo: delete all tasks with a dueDate in 2016
|
||||
System.out.println("\nDeleting all tasks with a dueDate in 2016");
|
||||
hqlQuery = "from Task where dueDate < :paramDate";
|
||||
List<Task> tasksToDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramDate", sdf.parse("12-31-2016"))
|
||||
.getResultList();
|
||||
for(Task theTask : tasksToDelete) {
|
||||
System.out.println("Deleting task:" + theTask.toString());
|
||||
session.delete(theTask);
|
||||
}
|
||||
|
||||
// Show tasks after the 'Delete' operation - there should be 0 tasks
|
||||
System.out.println("\nTasks after delete:");
|
||||
hqlQuery = "from Task";
|
||||
List<Task> tasksAfterDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList();
|
||||
if(tasksAfterDelete.isEmpty()) {
|
||||
System.out.println("[None]");
|
||||
}
|
||||
else {
|
||||
for(Task theTask : tasksAfterDelete) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
}
|
||||
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
System.out.println("All done.");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this
|
||||
// sample.
|
||||
private void createSampleDatabase() throws java.sql.SQLException {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
String url = this.connectionUrl + ";databaseName=master;" + "user=" + this.userName + ";password="
|
||||
+ this.password;
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(url)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database '" + this.sampleDatabaseName + "' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [" + this.sampleDatabaseName + "]; CREATE DATABASE ["
|
||||
+ this.sampleDatabaseName + "]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create Hibernate configuration via code instead of using a
|
||||
// 'hibernate.cfg.xml' file.
|
||||
private Configuration createHibernateConfiguration() {
|
||||
String url = this.connectionUrl + ";databaseName=" + this.sampleDatabaseName;
|
||||
Configuration cfg = new Configuration()
|
||||
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
|
||||
.setProperty("hibernate.connection.url", url)
|
||||
.setProperty("hibernate.connection.username", this.userName)
|
||||
.setProperty("hibernate.connection.password", this.password)
|
||||
.setProperty("hibernate.connection.autocommit", "true")
|
||||
.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// Tell Hibernate to use the 'SQL Server' dialect when dynamically
|
||||
// generating SQL queries
|
||||
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
|
||||
|
||||
// Tell Hibernate to show the generated T-SQL
|
||||
cfg.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// This is ok during development, but not recommended in production
|
||||
// See: http://stackoverflow.com/questions/221379/hibernate-hbm2ddl-auto-update-in-production
|
||||
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.Date;
|
||||
import javax.persistence.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Tasks")
|
||||
public class Task {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String title;
|
||||
private Boolean isComplete;
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Date dueDate;
|
||||
|
||||
// Specify a Many:1 mapping between Task and User
|
||||
@ManyToOne
|
||||
private User user;
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate, User user) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getDueDate() {
|
||||
return this.dueDate;
|
||||
}
|
||||
|
||||
public void setDueDate(Date dueDate) {
|
||||
this.dueDate = dueDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
|
||||
return "Task [id=" + this.id + ", title=" + this.title + ", dueDate=" + ft.format(this.dueDate)
|
||||
+ ", isComplete=" + this.isComplete.toString() + "]";
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
// Specify a 1:Many mapping between User and Task via the "user" field in
|
||||
// the "Tasks" class.
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
private List<Task> tasks = new ArrayList<Task>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return this.firstName + " " + this.lastName;
|
||||
}
|
||||
|
||||
public List<Task> getTasks() {
|
||||
return tasks;
|
||||
}
|
||||
|
||||
public void setTasks(List<Task> tasks) {
|
||||
this.tasks = tasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [id=" + this.id + ", name=" + this.getFullName() + "]";
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("Connect to SQL Server and demo Create, Read, Update and Delete operations.");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database 'SampleDB' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [SampleDB]; CREATE DATABASE [SampleDB]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Create a Table and insert some sample data
|
||||
System.out.print("Creating sample table with data, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("USE SampleDB; ").append("CREATE TABLE Employees ( ")
|
||||
.append(" Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, ").append(" Name NVARCHAR(50), ")
|
||||
.append(" Location NVARCHAR(50) ").append("); ")
|
||||
.append("INSERT INTO Employees (Name, Location) VALUES ").append("(N'Jared', N'Australia'), ")
|
||||
.append("(N'Nikita', N'India'), ").append("(N'Tom', N'Germany'); ").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// INSERT demo
|
||||
System.out.print("Inserting a new row into table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("INSERT Employees (Name, Location) ").append("VALUES (?, ?);")
|
||||
.toString();
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, "Jake");
|
||||
statement.setString(2, "United States");
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) inserted");
|
||||
}
|
||||
|
||||
// UPDATE demo
|
||||
String userToUpdate = "Nikita";
|
||||
System.out.print("Updating 'Location' for user '" + userToUpdate + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "UPDATE Employees SET Location = N'United States' WHERE Name = ?";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToUpdate);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) updated");
|
||||
}
|
||||
|
||||
// DELETE demo
|
||||
String userToDelete = "Jared";
|
||||
System.out.print("Deleting user '" + userToDelete + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "DELETE FROM Employees WHERE Name = ?;";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToDelete);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) deleted");
|
||||
}
|
||||
|
||||
// READ demo
|
||||
System.out.print("Reading data from table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "SELECT Id, Name, Location FROM Employees;";
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
System.out.println(
|
||||
resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("All done.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("*** SQL Server Columnstore demo ***");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create an example database
|
||||
System.out.print("Dropping and creating database 'Example_Columnstore' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [Example_Columnstore]; CREATE DATABASE [Example_Columnstore]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
// Insert 5 million rows into the table 'Table_with_5M_rows'
|
||||
System.out.print(
|
||||
"Inserting 5 million rows into table 'Table_with_5M_rows'. This takes ~15 seconds, please wait ... ");
|
||||
sql = new StringBuilder().append("USE Example_Columnstore; ")
|
||||
.append("WITH a AS (SELECT * FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS a(a))")
|
||||
.append("SELECT TOP(5000000)")
|
||||
.append("ROW_NUMBER() OVER (ORDER BY a.a) AS OrderItemId ")
|
||||
.append(",a.a + b.a + c.a + d.a + e.a + f.a + g.a + h.a AS OrderId ")
|
||||
.append(",a.a * 10 AS Price ")
|
||||
.append(",CONCAT(a.a, N' ', b.a, N' ', c.a, N' ', d.a, N' ', e.a, N' ', f.a, N' ', g.a, N' ', h.a) AS ProductName ")
|
||||
.append("INTO Table_with_5M_rows ")
|
||||
.append("FROM a, a AS b, a AS c, a AS d, a AS e, a AS f, a AS g, a AS h;").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute SQL query without a columnstore index
|
||||
long elapsedTimeWithoutIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITHOUT columnstore index: " + elapsedTimeWithoutIndex + "ms");
|
||||
|
||||
System.out.print("Adding a columnstore to table 'Table_with_5M_rows' ... ");
|
||||
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_5M_rows;";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute the same SQL query again after the columnstore index is added
|
||||
long elapsedTimeWithIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITH columnstore index: " + elapsedTimeWithIndex + "ms");
|
||||
|
||||
// Calculate performance gain from adding columnstore index
|
||||
System.out.println("Performance improvement with columnstore index: " + elapsedTimeWithoutIndex/elapsedTimeWithIndex + "x!");
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static long SumPrice (Connection connection){
|
||||
String sql = "SELECT SUM(Price) FROM Table_with_5M_rows;";
|
||||
long startTime = System.currentTimeMillis();
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
long elapsedTime = System.currentTimeMillis() - startTime;
|
||||
return elapsedTime;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerHibernateSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerHibernateSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>5.2.3.Final</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.DriverManager;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
|
||||
/**
|
||||
* Java CRUD sample with Hibernate and SQL Server
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433"; // update me
|
||||
String userName = "sa"; // update me
|
||||
String password = "your_password"; // update me
|
||||
String sampleDatabaseName = "SampleDB";
|
||||
|
||||
// Main entry point
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
app.runDemo();
|
||||
}
|
||||
|
||||
// Helper to run the demp app
|
||||
public void runDemo()
|
||||
{
|
||||
// Configure Hibernate logging to only log SEVERE errors
|
||||
@SuppressWarnings("unused")
|
||||
org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
|
||||
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.SEVERE);
|
||||
|
||||
System.out.println("**Java CRUD sample with Hibernate and SQL Server **\n");
|
||||
try {
|
||||
// We're creating the Hibernate configuration via code. An alternative is to use a 'hibernate.cfg.xml' file.
|
||||
Configuration cfg = createHibernateConfiguration();
|
||||
|
||||
// We're mapping POJO classes to Tables via Hibernate Annotations. An alternative is to use Hibernate mapping xml files.
|
||||
cfg.addAnnotatedClass(User.class);
|
||||
cfg.addAnnotatedClass(Task.class);
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this sample.
|
||||
createSampleDatabase();
|
||||
|
||||
// Create the Hibernate SessionFactory and Session.
|
||||
// This causes Hibernate to create Tables and Relationships in the database from our Annotated classes.
|
||||
try (SessionFactory sessionFactory = cfg.buildSessionFactory();
|
||||
Session session = sessionFactory.openSession()) {
|
||||
|
||||
System.out.println("Created database schema from Java classes.\n");
|
||||
session.beginTransaction();
|
||||
|
||||
// Create demo: Create a User instance and save it to the database
|
||||
User newUser = new User("Anna", "Shrestinian");
|
||||
session.save(newUser);
|
||||
System.out.println("Created User: " + newUser.toString());
|
||||
|
||||
// Create demo: Create a Task instance and save it to the database
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
|
||||
Task newTask = new Task("Ship Helsinki", sdf.parse("04-01-2017"));
|
||||
session.save(newTask);
|
||||
System.out.println("Created Task: " + newTask.toString());
|
||||
|
||||
// Association demo: Assign task to user
|
||||
newTask.setUser(newUser);
|
||||
session.save(newTask);
|
||||
System.out.println("Assigned Task: '" + newTask.getTitle() + "' to user '" + newUser.getFullName() + "'\n");
|
||||
|
||||
// Read demo: find incomplete tasks assigned to user 'Anna'
|
||||
System.out.println("Incomplete tasks assigned to 'Anna':");
|
||||
String hqlQuery = "from Task where isComplete = false and user.firstName = :paramFirstName";
|
||||
List<Task> incompleteTasks = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramFirstName", "Anna")
|
||||
.getResultList();
|
||||
for(Task theTask : incompleteTasks) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
|
||||
// Update demo: change the 'dueDate' of a task
|
||||
hqlQuery = "from Task";
|
||||
Task taskToUpdate = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList()
|
||||
.get(0); // get the first task
|
||||
System.out.println("\nUpdating task: " + taskToUpdate.toString());
|
||||
taskToUpdate.setDueDate(sdf.parse("06-30-2016"));
|
||||
session.save(taskToUpdate);
|
||||
System.out.println("dueDate changed: " + taskToUpdate.toString());
|
||||
|
||||
// Delete demo: delete all tasks with a dueDate in 2016
|
||||
System.out.println("\nDeleting all tasks with a dueDate in 2016");
|
||||
hqlQuery = "from Task where dueDate < :paramDate";
|
||||
List<Task> tasksToDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramDate", sdf.parse("12-31-2016"))
|
||||
.getResultList();
|
||||
for(Task theTask : tasksToDelete) {
|
||||
System.out.println("Deleting task:" + theTask.toString());
|
||||
session.delete(theTask);
|
||||
}
|
||||
|
||||
// Show tasks after the 'Delete' operation - there should be 0 tasks
|
||||
System.out.println("\nTasks after delete:");
|
||||
hqlQuery = "from Task";
|
||||
List<Task> tasksAfterDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList();
|
||||
if(tasksAfterDelete.isEmpty()) {
|
||||
System.out.println("[None]");
|
||||
}
|
||||
else {
|
||||
for(Task theTask : tasksAfterDelete) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
}
|
||||
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
System.out.println("All done.");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this
|
||||
// sample.
|
||||
private void createSampleDatabase() throws java.sql.SQLException {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
String url = this.connectionUrl + ";databaseName=master;" + "user=" + this.userName + ";password="
|
||||
+ this.password;
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(url)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database '" + this.sampleDatabaseName + "' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [" + this.sampleDatabaseName + "]; CREATE DATABASE ["
|
||||
+ this.sampleDatabaseName + "]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create Hibernate configuration via code instead of using a
|
||||
// 'hibernate.cfg.xml' file.
|
||||
private Configuration createHibernateConfiguration() {
|
||||
String url = this.connectionUrl + ";databaseName=" + this.sampleDatabaseName;
|
||||
Configuration cfg = new Configuration()
|
||||
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
|
||||
.setProperty("hibernate.connection.url", url)
|
||||
.setProperty("hibernate.connection.username", this.userName)
|
||||
.setProperty("hibernate.connection.password", this.password)
|
||||
.setProperty("hibernate.connection.autocommit", "true")
|
||||
.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// Tell Hibernate to use the 'SQL Server' dialect when dynamically
|
||||
// generating SQL queries
|
||||
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
|
||||
|
||||
// Tell Hibernate to show the generated T-SQL
|
||||
cfg.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// This is ok during development, but not recommended in production
|
||||
// See: http://stackoverflow.com/questions/221379/hibernate-hbm2ddl-auto-update-in-production
|
||||
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.Date;
|
||||
import javax.persistence.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Tasks")
|
||||
public class Task {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String title;
|
||||
private Boolean isComplete;
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Date dueDate;
|
||||
|
||||
// Specify a Many:1 mapping between Task and User
|
||||
@ManyToOne
|
||||
private User user;
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate, User user) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getDueDate() {
|
||||
return this.dueDate;
|
||||
}
|
||||
|
||||
public void setDueDate(Date dueDate) {
|
||||
this.dueDate = dueDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
|
||||
return "Task [id=" + this.id + ", title=" + this.title + ", dueDate=" + ft.format(this.dueDate)
|
||||
+ ", isComplete=" + this.isComplete.toString() + "]";
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
// Specify a 1:Many mapping between User and Task via the "user" field in
|
||||
// the "Tasks" class.
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
private List<Task> tasks = new ArrayList<Task>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return this.firstName + " " + this.lastName;
|
||||
}
|
||||
|
||||
public List<Task> getTasks() {
|
||||
return tasks;
|
||||
}
|
||||
|
||||
public void setTasks(List<Task> tasks) {
|
||||
this.tasks = tasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [id=" + this.id + ", name=" + this.getFullName() + "]";
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("Connect to SQL Server and demo Create, Read, Update and Delete operations.");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database 'SampleDB' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [SampleDB]; CREATE DATABASE [SampleDB]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Create a Table and insert some sample data
|
||||
System.out.print("Creating sample table with data, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("USE SampleDB; ").append("CREATE TABLE Employees ( ")
|
||||
.append(" Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, ").append(" Name NVARCHAR(50), ")
|
||||
.append(" Location NVARCHAR(50) ").append("); ")
|
||||
.append("INSERT INTO Employees (Name, Location) VALUES ").append("(N'Jared', N'Australia'), ")
|
||||
.append("(N'Nikita', N'India'), ").append("(N'Tom', N'Germany'); ").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// INSERT demo
|
||||
System.out.print("Inserting a new row into table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("INSERT Employees (Name, Location) ").append("VALUES (?, ?);")
|
||||
.toString();
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, "Jake");
|
||||
statement.setString(2, "United States");
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) inserted");
|
||||
}
|
||||
|
||||
// UPDATE demo
|
||||
String userToUpdate = "Nikita";
|
||||
System.out.print("Updating 'Location' for user '" + userToUpdate + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "UPDATE Employees SET Location = N'United States' WHERE Name = ?";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToUpdate);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) updated");
|
||||
}
|
||||
|
||||
// DELETE demo
|
||||
String userToDelete = "Jared";
|
||||
System.out.print("Deleting user '" + userToDelete + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "DELETE FROM Employees WHERE Name = ?;";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToDelete);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) deleted");
|
||||
}
|
||||
|
||||
// READ demo
|
||||
System.out.print("Reading data from table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "SELECT Id, Name, Location FROM Employees;";
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
System.out.println(
|
||||
resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("All done.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("*** SQL Server Columnstore demo ***");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create an example database
|
||||
System.out.print("Dropping and creating database 'Example_Columnstore' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [Example_Columnstore]; CREATE DATABASE [Example_Columnstore]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
// Insert 5 million rows into the table 'Table_with_5M_rows'
|
||||
System.out.print(
|
||||
"Inserting 5 million rows into table 'Table_with_5M_rows'. This takes ~15 seconds, please wait ... ");
|
||||
sql = new StringBuilder().append("USE Example_Columnstore; ")
|
||||
.append("WITH a AS (SELECT * FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS a(a))")
|
||||
.append("SELECT TOP(5000000)")
|
||||
.append("ROW_NUMBER() OVER (ORDER BY a.a) AS OrderItemId ")
|
||||
.append(",a.a + b.a + c.a + d.a + e.a + f.a + g.a + h.a AS OrderId ")
|
||||
.append(",a.a * 10 AS Price ")
|
||||
.append(",CONCAT(a.a, N' ', b.a, N' ', c.a, N' ', d.a, N' ', e.a, N' ', f.a, N' ', g.a, N' ', h.a) AS ProductName ")
|
||||
.append("INTO Table_with_5M_rows ")
|
||||
.append("FROM a, a AS b, a AS c, a AS d, a AS e, a AS f, a AS g, a AS h;").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute SQL query without a columnstore index
|
||||
long elapsedTimeWithoutIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITHOUT columnstore index: " + elapsedTimeWithoutIndex + "ms");
|
||||
|
||||
System.out.print("Adding a columnstore to table 'Table_with_5M_rows' ... ");
|
||||
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_5M_rows;";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute the same SQL query again after the columnstore index is added
|
||||
long elapsedTimeWithIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITH columnstore index: " + elapsedTimeWithIndex + "ms");
|
||||
|
||||
// Calculate performance gain from adding columnstore index
|
||||
System.out.println("Performance improvement with columnstore index: " + elapsedTimeWithoutIndex/elapsedTimeWithIndex + "x!");
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static long SumPrice (Connection connection){
|
||||
String sql = "SELECT SUM(Price) FROM Table_with_5M_rows;";
|
||||
long startTime = System.currentTimeMillis();
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
long elapsedTime = System.currentTimeMillis() - startTime;
|
||||
return elapsedTime;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerHibernateSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerHibernateSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>5.2.3.Final</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.DriverManager;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
|
||||
/**
|
||||
* Java CRUD sample with Hibernate and SQL Server
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433"; // update me
|
||||
String userName = "sa"; // update me
|
||||
String password = "your_password"; // update me
|
||||
String sampleDatabaseName = "SampleDB";
|
||||
|
||||
// Main entry point
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
app.runDemo();
|
||||
}
|
||||
|
||||
// Helper to run the demp app
|
||||
public void runDemo()
|
||||
{
|
||||
// Configure Hibernate logging to only log SEVERE errors
|
||||
@SuppressWarnings("unused")
|
||||
org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
|
||||
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.SEVERE);
|
||||
|
||||
System.out.println("**Java CRUD sample with Hibernate and SQL Server **\n");
|
||||
try {
|
||||
// We're creating the Hibernate configuration via code. An alternative is to use a 'hibernate.cfg.xml' file.
|
||||
Configuration cfg = createHibernateConfiguration();
|
||||
|
||||
// We're mapping POJO classes to Tables via Hibernate Annotations. An alternative is to use Hibernate mapping xml files.
|
||||
cfg.addAnnotatedClass(User.class);
|
||||
cfg.addAnnotatedClass(Task.class);
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this sample.
|
||||
createSampleDatabase();
|
||||
|
||||
// Create the Hibernate SessionFactory and Session.
|
||||
// This causes Hibernate to create Tables and Relationships in the database from our Annotated classes.
|
||||
try (SessionFactory sessionFactory = cfg.buildSessionFactory();
|
||||
Session session = sessionFactory.openSession()) {
|
||||
|
||||
System.out.println("Created database schema from Java classes.\n");
|
||||
session.beginTransaction();
|
||||
|
||||
// Create demo: Create a User instance and save it to the database
|
||||
User newUser = new User("Anna", "Shrestinian");
|
||||
session.save(newUser);
|
||||
System.out.println("Created User: " + newUser.toString());
|
||||
|
||||
// Create demo: Create a Task instance and save it to the database
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
|
||||
Task newTask = new Task("Ship Helsinki", sdf.parse("04-01-2017"));
|
||||
session.save(newTask);
|
||||
System.out.println("Created Task: " + newTask.toString());
|
||||
|
||||
// Association demo: Assign task to user
|
||||
newTask.setUser(newUser);
|
||||
session.save(newTask);
|
||||
System.out.println("Assigned Task: '" + newTask.getTitle() + "' to user '" + newUser.getFullName() + "'\n");
|
||||
|
||||
// Read demo: find incomplete tasks assigned to user 'Anna'
|
||||
System.out.println("Incomplete tasks assigned to 'Anna':");
|
||||
String hqlQuery = "from Task where isComplete = false and user.firstName = :paramFirstName";
|
||||
List<Task> incompleteTasks = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramFirstName", "Anna")
|
||||
.getResultList();
|
||||
for(Task theTask : incompleteTasks) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
|
||||
// Update demo: change the 'dueDate' of a task
|
||||
hqlQuery = "from Task";
|
||||
Task taskToUpdate = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList()
|
||||
.get(0); // get the first task
|
||||
System.out.println("\nUpdating task: " + taskToUpdate.toString());
|
||||
taskToUpdate.setDueDate(sdf.parse("06-30-2016"));
|
||||
session.save(taskToUpdate);
|
||||
System.out.println("dueDate changed: " + taskToUpdate.toString());
|
||||
|
||||
// Delete demo: delete all tasks with a dueDate in 2016
|
||||
System.out.println("\nDeleting all tasks with a dueDate in 2016");
|
||||
hqlQuery = "from Task where dueDate < :paramDate";
|
||||
List<Task> tasksToDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramDate", sdf.parse("12-31-2016"))
|
||||
.getResultList();
|
||||
for(Task theTask : tasksToDelete) {
|
||||
System.out.println("Deleting task:" + theTask.toString());
|
||||
session.delete(theTask);
|
||||
}
|
||||
|
||||
// Show tasks after the 'Delete' operation - there should be 0 tasks
|
||||
System.out.println("\nTasks after delete:");
|
||||
hqlQuery = "from Task";
|
||||
List<Task> tasksAfterDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList();
|
||||
if(tasksAfterDelete.isEmpty()) {
|
||||
System.out.println("[None]");
|
||||
}
|
||||
else {
|
||||
for(Task theTask : tasksAfterDelete) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
}
|
||||
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
System.out.println("All done.");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this
|
||||
// sample.
|
||||
private void createSampleDatabase() throws java.sql.SQLException {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
String url = this.connectionUrl + ";databaseName=master;" + "user=" + this.userName + ";password="
|
||||
+ this.password;
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(url)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database '" + this.sampleDatabaseName + "' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [" + this.sampleDatabaseName + "]; CREATE DATABASE ["
|
||||
+ this.sampleDatabaseName + "]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create Hibernate configuration via code instead of using a
|
||||
// 'hibernate.cfg.xml' file.
|
||||
private Configuration createHibernateConfiguration() {
|
||||
String url = this.connectionUrl + ";databaseName=" + this.sampleDatabaseName;
|
||||
Configuration cfg = new Configuration()
|
||||
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
|
||||
.setProperty("hibernate.connection.url", url)
|
||||
.setProperty("hibernate.connection.username", this.userName)
|
||||
.setProperty("hibernate.connection.password", this.password)
|
||||
.setProperty("hibernate.connection.autocommit", "true")
|
||||
.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// Tell Hibernate to use the 'SQL Server' dialect when dynamically
|
||||
// generating SQL queries
|
||||
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
|
||||
|
||||
// Tell Hibernate to show the generated T-SQL
|
||||
cfg.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// This is ok during development, but not recommended in production
|
||||
// See: http://stackoverflow.com/questions/221379/hibernate-hbm2ddl-auto-update-in-production
|
||||
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.Date;
|
||||
import javax.persistence.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Tasks")
|
||||
public class Task {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String title;
|
||||
private Boolean isComplete;
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Date dueDate;
|
||||
|
||||
// Specify a Many:1 mapping between Task and User
|
||||
@ManyToOne
|
||||
private User user;
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate, User user) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getDueDate() {
|
||||
return this.dueDate;
|
||||
}
|
||||
|
||||
public void setDueDate(Date dueDate) {
|
||||
this.dueDate = dueDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
|
||||
return "Task [id=" + this.id + ", title=" + this.title + ", dueDate=" + ft.format(this.dueDate)
|
||||
+ ", isComplete=" + this.isComplete.toString() + "]";
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
// Specify a 1:Many mapping between User and Task via the "user" field in
|
||||
// the "Tasks" class.
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
private List<Task> tasks = new ArrayList<Task>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return this.firstName + " " + this.lastName;
|
||||
}
|
||||
|
||||
public List<Task> getTasks() {
|
||||
return tasks;
|
||||
}
|
||||
|
||||
public void setTasks(List<Task> tasks) {
|
||||
this.tasks = tasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [id=" + this.id + ", name=" + this.getFullName() + "]";
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("Connect to SQL Server and demo Create, Read, Update and Delete operations.");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database 'SampleDB' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [SampleDB]; CREATE DATABASE [SampleDB]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Create a Table and insert some sample data
|
||||
System.out.print("Creating sample table with data, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("USE SampleDB; ").append("CREATE TABLE Employees ( ")
|
||||
.append(" Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, ").append(" Name NVARCHAR(50), ")
|
||||
.append(" Location NVARCHAR(50) ").append("); ")
|
||||
.append("INSERT INTO Employees (Name, Location) VALUES ").append("(N'Jared', N'Australia'), ")
|
||||
.append("(N'Nikita', N'India'), ").append("(N'Tom', N'Germany'); ").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// INSERT demo
|
||||
System.out.print("Inserting a new row into table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("INSERT Employees (Name, Location) ").append("VALUES (?, ?);")
|
||||
.toString();
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, "Jake");
|
||||
statement.setString(2, "United States");
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) inserted");
|
||||
}
|
||||
|
||||
// UPDATE demo
|
||||
String userToUpdate = "Nikita";
|
||||
System.out.print("Updating 'Location' for user '" + userToUpdate + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "UPDATE Employees SET Location = N'United States' WHERE Name = ?";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToUpdate);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) updated");
|
||||
}
|
||||
|
||||
// DELETE demo
|
||||
String userToDelete = "Jared";
|
||||
System.out.print("Deleting user '" + userToDelete + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "DELETE FROM Employees WHERE Name = ?;";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToDelete);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) deleted");
|
||||
}
|
||||
|
||||
// READ demo
|
||||
System.out.print("Reading data from table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "SELECT Id, Name, Location FROM Employees;";
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
System.out.println(
|
||||
resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("All done.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("*** SQL Server Columnstore demo ***");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create an example database
|
||||
System.out.print("Dropping and creating database 'Example_Columnstore' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [Example_Columnstore]; CREATE DATABASE [Example_Columnstore]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
// Insert 5 million rows into the table 'Table_with_5M_rows'
|
||||
System.out.print(
|
||||
"Inserting 5 million rows into table 'Table_with_5M_rows'. This takes ~15 seconds, please wait ... ");
|
||||
sql = new StringBuilder().append("USE Example_Columnstore; ")
|
||||
.append("WITH a AS (SELECT * FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS a(a))")
|
||||
.append("SELECT TOP(5000000)")
|
||||
.append("ROW_NUMBER() OVER (ORDER BY a.a) AS OrderItemId ")
|
||||
.append(",a.a + b.a + c.a + d.a + e.a + f.a + g.a + h.a AS OrderId ")
|
||||
.append(",a.a * 10 AS Price ")
|
||||
.append(",CONCAT(a.a, N' ', b.a, N' ', c.a, N' ', d.a, N' ', e.a, N' ', f.a, N' ', g.a, N' ', h.a) AS ProductName ")
|
||||
.append("INTO Table_with_5M_rows ")
|
||||
.append("FROM a, a AS b, a AS c, a AS d, a AS e, a AS f, a AS g, a AS h;").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute SQL query without a columnstore index
|
||||
long elapsedTimeWithoutIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITHOUT columnstore index: " + elapsedTimeWithoutIndex + "ms");
|
||||
|
||||
System.out.print("Adding a columnstore to table 'Table_with_5M_rows' ... ");
|
||||
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_5M_rows;";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Execute the same SQL query again after the columnstore index is added
|
||||
long elapsedTimeWithIndex = SumPrice(connection);
|
||||
System.out.println("Query time WITH columnstore index: " + elapsedTimeWithIndex + "ms");
|
||||
|
||||
// Calculate performance gain from adding columnstore index
|
||||
System.out.println("Performance improvement with columnstore index: " + elapsedTimeWithoutIndex/elapsedTimeWithIndex + "x!");
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static long SumPrice (Connection connection){
|
||||
String sql = "SELECT SUM(Price) FROM Table_with_5M_rows;";
|
||||
long startTime = System.currentTimeMillis();
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
long elapsedTime = System.currentTimeMillis() - startTime;
|
||||
return elapsedTime;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerHibernateSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerHibernateSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>5.2.3.Final</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.DriverManager;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
|
||||
/**
|
||||
* Java CRUD sample with Hibernate and SQL Server
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433"; // update me
|
||||
String userName = "sa"; // update me
|
||||
String password = "your_password"; // update me
|
||||
String sampleDatabaseName = "SampleDB";
|
||||
|
||||
// Main entry point
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
app.runDemo();
|
||||
}
|
||||
|
||||
// Helper to run the demp app
|
||||
public void runDemo()
|
||||
{
|
||||
// Configure Hibernate logging to only log SEVERE errors
|
||||
@SuppressWarnings("unused")
|
||||
org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
|
||||
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.SEVERE);
|
||||
|
||||
System.out.println("**Java CRUD sample with Hibernate and SQL Server **\n");
|
||||
try {
|
||||
// We're creating the Hibernate configuration via code. An alternative is to use a 'hibernate.cfg.xml' file.
|
||||
Configuration cfg = createHibernateConfiguration();
|
||||
|
||||
// We're mapping POJO classes to Tables via Hibernate Annotations. An alternative is to use Hibernate mapping xml files.
|
||||
cfg.addAnnotatedClass(User.class);
|
||||
cfg.addAnnotatedClass(Task.class);
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this sample.
|
||||
createSampleDatabase();
|
||||
|
||||
// Create the Hibernate SessionFactory and Session.
|
||||
// This causes Hibernate to create Tables and Relationships in the database from our Annotated classes.
|
||||
try (SessionFactory sessionFactory = cfg.buildSessionFactory();
|
||||
Session session = sessionFactory.openSession()) {
|
||||
|
||||
System.out.println("Created database schema from Java classes.\n");
|
||||
session.beginTransaction();
|
||||
|
||||
// Create demo: Create a User instance and save it to the database
|
||||
User newUser = new User("Anna", "Shrestinian");
|
||||
session.save(newUser);
|
||||
System.out.println("Created User: " + newUser.toString());
|
||||
|
||||
// Create demo: Create a Task instance and save it to the database
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
|
||||
Task newTask = new Task("Ship Helsinki", sdf.parse("04-01-2017"));
|
||||
session.save(newTask);
|
||||
System.out.println("Created Task: " + newTask.toString());
|
||||
|
||||
// Association demo: Assign task to user
|
||||
newTask.setUser(newUser);
|
||||
session.save(newTask);
|
||||
System.out.println("Assigned Task: '" + newTask.getTitle() + "' to user '" + newUser.getFullName() + "'\n");
|
||||
|
||||
// Read demo: find incomplete tasks assigned to user 'Anna'
|
||||
System.out.println("Incomplete tasks assigned to 'Anna':");
|
||||
String hqlQuery = "from Task where isComplete = false and user.firstName = :paramFirstName";
|
||||
List<Task> incompleteTasks = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramFirstName", "Anna")
|
||||
.getResultList();
|
||||
for(Task theTask : incompleteTasks) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
|
||||
// Update demo: change the 'dueDate' of a task
|
||||
hqlQuery = "from Task";
|
||||
Task taskToUpdate = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList()
|
||||
.get(0); // get the first task
|
||||
System.out.println("\nUpdating task: " + taskToUpdate.toString());
|
||||
taskToUpdate.setDueDate(sdf.parse("06-30-2016"));
|
||||
session.save(taskToUpdate);
|
||||
System.out.println("dueDate changed: " + taskToUpdate.toString());
|
||||
|
||||
// Delete demo: delete all tasks with a dueDate in 2016
|
||||
System.out.println("\nDeleting all tasks with a dueDate in 2016");
|
||||
hqlQuery = "from Task where dueDate < :paramDate";
|
||||
List<Task> tasksToDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.setParameter("paramDate", sdf.parse("12-31-2016"))
|
||||
.getResultList();
|
||||
for(Task theTask : tasksToDelete) {
|
||||
System.out.println("Deleting task:" + theTask.toString());
|
||||
session.delete(theTask);
|
||||
}
|
||||
|
||||
// Show tasks after the 'Delete' operation - there should be 0 tasks
|
||||
System.out.println("\nTasks after delete:");
|
||||
hqlQuery = "from Task";
|
||||
List<Task> tasksAfterDelete = session.createQuery(hqlQuery, Task.class)
|
||||
.getResultList();
|
||||
if(tasksAfterDelete.isEmpty()) {
|
||||
System.out.println("[None]");
|
||||
}
|
||||
else {
|
||||
for(Task theTask : tasksAfterDelete) {
|
||||
System.out.println(theTask.toString());
|
||||
}
|
||||
}
|
||||
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
System.out.println("All done.");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Hibernate needs an existing database. Use JDBC to create one for this
|
||||
// sample.
|
||||
private void createSampleDatabase() throws java.sql.SQLException {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
String url = this.connectionUrl + ";databaseName=master;" + "user=" + this.userName + ";password="
|
||||
+ this.password;
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(url)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database '" + this.sampleDatabaseName + "' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [" + this.sampleDatabaseName + "]; CREATE DATABASE ["
|
||||
+ this.sampleDatabaseName + "]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create Hibernate configuration via code instead of using a
|
||||
// 'hibernate.cfg.xml' file.
|
||||
private Configuration createHibernateConfiguration() {
|
||||
String url = this.connectionUrl + ";databaseName=" + this.sampleDatabaseName;
|
||||
Configuration cfg = new Configuration()
|
||||
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
|
||||
.setProperty("hibernate.connection.url", url)
|
||||
.setProperty("hibernate.connection.username", this.userName)
|
||||
.setProperty("hibernate.connection.password", this.password)
|
||||
.setProperty("hibernate.connection.autocommit", "true")
|
||||
.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// Tell Hibernate to use the 'SQL Server' dialect when dynamically
|
||||
// generating SQL queries
|
||||
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
|
||||
|
||||
// Tell Hibernate to show the generated T-SQL
|
||||
cfg.setProperty("hibernate.show_sql", "false");
|
||||
|
||||
// This is ok during development, but not recommended in production
|
||||
// See: http://stackoverflow.com/questions/221379/hibernate-hbm2ddl-auto-update-in-production
|
||||
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.Date;
|
||||
import javax.persistence.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Tasks")
|
||||
public class Task {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String title;
|
||||
private Boolean isComplete;
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Date dueDate;
|
||||
|
||||
// Specify a Many:1 mapping between Task and User
|
||||
@ManyToOne
|
||||
private User user;
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
}
|
||||
|
||||
public Task(String title, Date dueDate, User user) {
|
||||
this.title = title;
|
||||
this.dueDate = dueDate;
|
||||
this.isComplete = false;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Date getDueDate() {
|
||||
return this.dueDate;
|
||||
}
|
||||
|
||||
public void setDueDate(Date dueDate) {
|
||||
this.dueDate = dueDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
|
||||
return "Task [id=" + this.id + ", title=" + this.title + ", dueDate=" + ft.format(this.dueDate)
|
||||
+ ", isComplete=" + this.isComplete.toString() + "]";
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
// Specify a 1:Many mapping between User and Task via the "user" field in
|
||||
// the "Tasks" class.
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
private List<Task> tasks = new ArrayList<Task>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return this.firstName + " " + this.lastName;
|
||||
}
|
||||
|
||||
public List<Task> getTasks() {
|
||||
return tasks;
|
||||
}
|
||||
|
||||
public void setTasks(List<Task> tasks) {
|
||||
this.tasks = tasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [id=" + this.id + ", name=" + this.getFullName() + "]";
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.sqlsamples</groupId>
|
||||
<artifactId>SqlServerSample</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0.0</version>
|
||||
<name>SqlServerSample</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<!-- your existing properties -->
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<version>6.1.0.jre8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("Connect to SQL Server and demo Create, Read, Update and Delete operations.");
|
||||
|
||||
//Update the username and password below
|
||||
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
|
||||
|
||||
try {
|
||||
// Load SQL Server JDBC driver and establish connection.
|
||||
System.out.print("Connecting to SQL Server ... ");
|
||||
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
|
||||
System.out.println("Done.");
|
||||
|
||||
// Create a sample database
|
||||
System.out.print("Dropping and creating database 'SampleDB' ... ");
|
||||
String sql = "DROP DATABASE IF EXISTS [SampleDB]; CREATE DATABASE [SampleDB]";
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// Create a Table and insert some sample data
|
||||
System.out.print("Creating sample table with data, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("USE SampleDB; ").append("CREATE TABLE Employees ( ")
|
||||
.append(" Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, ").append(" Name NVARCHAR(50), ")
|
||||
.append(" Location NVARCHAR(50) ").append("); ")
|
||||
.append("INSERT INTO Employees (Name, Location) VALUES ").append("(N'Jared', N'Australia'), ")
|
||||
.append("(N'Nikita', N'India'), ").append("(N'Tom', N'Germany'); ").toString();
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate(sql);
|
||||
System.out.println("Done.");
|
||||
}
|
||||
|
||||
// INSERT demo
|
||||
System.out.print("Inserting a new row into table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = new StringBuilder().append("INSERT Employees (Name, Location) ").append("VALUES (?, ?);")
|
||||
.toString();
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, "Jake");
|
||||
statement.setString(2, "United States");
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) inserted");
|
||||
}
|
||||
|
||||
// UPDATE demo
|
||||
String userToUpdate = "Nikita";
|
||||
System.out.print("Updating 'Location' for user '" + userToUpdate + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "UPDATE Employees SET Location = N'United States' WHERE Name = ?";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToUpdate);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) updated");
|
||||
}
|
||||
|
||||
// DELETE demo
|
||||
String userToDelete = "Jared";
|
||||
System.out.print("Deleting user '" + userToDelete + "', press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "DELETE FROM Employees WHERE Name = ?;";
|
||||
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, userToDelete);
|
||||
int rowsAffected = statement.executeUpdate();
|
||||
System.out.println(rowsAffected + " row(s) deleted");
|
||||
}
|
||||
|
||||
// READ demo
|
||||
System.out.print("Reading data from table, press ENTER to continue...");
|
||||
System.in.read();
|
||||
sql = "SELECT Id, Name, Location FROM Employees;";
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
while (resultSet.next()) {
|
||||
System.out.println(
|
||||
resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("All done.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.sqlsamples;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user