mirror of
https://github.com/Microsoft/sql-server-samples.git
synced 2025-12-08 14:58:54 +00:00
Remove C# Connect sample and rename folder to "tutorials"
This commit is contained in:
@@ -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 );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user