diff --git a/samples/connect/java/RHEL/SqlServerColumnstoreSample/pom.xml b/samples/connect/java/RHEL/SqlServerColumnstoreSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerColumnstoreSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/RHEL/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/RHEL/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..744171bc --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java @@ -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; + } +} \ No newline at end of file diff --git a/samples/connect/java/RHEL/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/RHEL/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/RHEL/SqlServerHibernateSample/pom.xml b/samples/connect/java/RHEL/SqlServerHibernateSample/pom.xml new file mode 100644 index 00000000..e4ec09d6 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerHibernateSample/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.sqlsamples + SqlServerHibernateSample + jar + 1.0.0 + SqlServerHibernateSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + org.hibernate + hibernate-core + 5.2.3.Final + + + diff --git a/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1383ca87 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java @@ -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 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 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 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; + } +} \ No newline at end of file diff --git a/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java b/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java new file mode 100644 index 00000000..5d6d60dd --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java @@ -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() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java b/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java new file mode 100644 index 00000000..552494d8 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java @@ -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 tasks = new ArrayList(); + + 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 getTasks() { + return tasks; + } + + public void setTasks(List tasks) { + this.tasks = tasks; + } + + @Override + public String toString() { + return "User [id=" + this.id + ", name=" + this.getFullName() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/RHEL/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/RHEL/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/RHEL/SqlServerSample/pom.xml b/samples/connect/java/RHEL/SqlServerSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/RHEL/SqlServerSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/RHEL/SqlServerSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1626fc25 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerSample/src/main/java/com/sqlsamples/App.java @@ -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(); + } + } +} \ No newline at end of file diff --git a/samples/connect/java/RHEL/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/RHEL/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/RHEL/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/pom.xml b/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..744171bc --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java @@ -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; + } +} \ No newline at end of file diff --git a/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/Ubuntu/SqlServerHibernateSample/pom.xml b/samples/connect/java/Ubuntu/SqlServerHibernateSample/pom.xml new file mode 100644 index 00000000..e4ec09d6 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerHibernateSample/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.sqlsamples + SqlServerHibernateSample + jar + 1.0.0 + SqlServerHibernateSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + org.hibernate + hibernate-core + 5.2.3.Final + + + diff --git a/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1383ca87 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java @@ -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 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 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 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; + } +} \ No newline at end of file diff --git a/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java new file mode 100644 index 00000000..5d6d60dd --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java @@ -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() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java new file mode 100644 index 00000000..552494d8 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java @@ -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 tasks = new ArrayList(); + + 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 getTasks() { + return tasks; + } + + public void setTasks(List tasks) { + this.tasks = tasks; + } + + @Override + public String toString() { + return "User [id=" + this.id + ", name=" + this.getFullName() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/Ubuntu/SqlServerSample/pom.xml b/samples/connect/java/Ubuntu/SqlServerSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/Ubuntu/SqlServerSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/Ubuntu/SqlServerSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1626fc25 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerSample/src/main/java/com/sqlsamples/App.java @@ -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(); + } + } +} \ No newline at end of file diff --git a/samples/connect/java/Ubuntu/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/Ubuntu/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/Ubuntu/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/Windows/SqlServerColumnstoreSample/pom.xml b/samples/connect/java/Windows/SqlServerColumnstoreSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/Windows/SqlServerColumnstoreSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/Windows/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/Windows/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..744171bc --- /dev/null +++ b/samples/connect/java/Windows/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java @@ -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; + } +} \ No newline at end of file diff --git a/samples/connect/java/Windows/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/Windows/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/Windows/SqlServerHibernateSample/pom.xml b/samples/connect/java/Windows/SqlServerHibernateSample/pom.xml new file mode 100644 index 00000000..e4ec09d6 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerHibernateSample/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.sqlsamples + SqlServerHibernateSample + jar + 1.0.0 + SqlServerHibernateSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + org.hibernate + hibernate-core + 5.2.3.Final + + + diff --git a/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1383ca87 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java @@ -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 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 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 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; + } +} \ No newline at end of file diff --git a/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java b/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java new file mode 100644 index 00000000..5d6d60dd --- /dev/null +++ b/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java @@ -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() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java b/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java new file mode 100644 index 00000000..552494d8 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java @@ -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 tasks = new ArrayList(); + + 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 getTasks() { + return tasks; + } + + public void setTasks(List tasks) { + this.tasks = tasks; + } + + @Override + public String toString() { + return "User [id=" + this.id + ", name=" + this.getFullName() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/Windows/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/Windows/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/Windows/SqlServerSample/pom.xml b/samples/connect/java/Windows/SqlServerSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/Windows/SqlServerSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/Windows/SqlServerSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/Windows/SqlServerSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1626fc25 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerSample/src/main/java/com/sqlsamples/App.java @@ -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(); + } + } +} \ No newline at end of file diff --git a/samples/connect/java/Windows/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/Windows/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/Windows/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/macOS/SqlServerColumnstoreSample/pom.xml b/samples/connect/java/macOS/SqlServerColumnstoreSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/macOS/SqlServerColumnstoreSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/macOS/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/macOS/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..744171bc --- /dev/null +++ b/samples/connect/java/macOS/SqlServerColumnstoreSample/src/main/java/com/sqlsamples/App.java @@ -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; + } +} \ No newline at end of file diff --git a/samples/connect/java/macOS/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/macOS/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerColumnstoreSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/macOS/SqlServerHibernateSample/pom.xml b/samples/connect/java/macOS/SqlServerHibernateSample/pom.xml new file mode 100644 index 00000000..e4ec09d6 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerHibernateSample/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.sqlsamples + SqlServerHibernateSample + jar + 1.0.0 + SqlServerHibernateSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + org.hibernate + hibernate-core + 5.2.3.Final + + + diff --git a/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1383ca87 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/App.java @@ -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 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 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 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; + } +} \ No newline at end of file diff --git a/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java b/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java new file mode 100644 index 00000000..5d6d60dd --- /dev/null +++ b/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/Task.java @@ -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() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java b/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java new file mode 100644 index 00000000..552494d8 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerHibernateSample/src/main/java/com/sqlsamples/User.java @@ -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 tasks = new ArrayList(); + + 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 getTasks() { + return tasks; + } + + public void setTasks(List tasks) { + this.tasks = tasks; + } + + @Override + public String toString() { + return "User [id=" + this.id + ", name=" + this.getFullName() + "]"; + } +} \ No newline at end of file diff --git a/samples/connect/java/macOS/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/macOS/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerHibernateSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +} diff --git a/samples/connect/java/macOS/SqlServerSample/pom.xml b/samples/connect/java/macOS/SqlServerSample/pom.xml new file mode 100644 index 00000000..e9a389ee --- /dev/null +++ b/samples/connect/java/macOS/SqlServerSample/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.sqlsamples + SqlServerSample + jar + 1.0.0 + SqlServerSample + http://maven.apache.org + + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + com.microsoft.sqlserver + mssql-jdbc + 6.1.0.jre8 + + + diff --git a/samples/connect/java/macOS/SqlServerSample/src/main/java/com/sqlsamples/App.java b/samples/connect/java/macOS/SqlServerSample/src/main/java/com/sqlsamples/App.java new file mode 100644 index 00000000..1626fc25 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerSample/src/main/java/com/sqlsamples/App.java @@ -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(); + } + } +} \ No newline at end of file diff --git a/samples/connect/java/macOS/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java b/samples/connect/java/macOS/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java new file mode 100644 index 00000000..58f4cc67 --- /dev/null +++ b/samples/connect/java/macOS/SqlServerSample/src/test/java/com/sqlsamples/AppTest.java @@ -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 ); + } +}